在指定数据源里面生成一个长度为 n 的不重复随机数组

710 阅读1分钟

题目

给定一个数组,及一个长度n,生成长度为n的不重复随机数组,n不大于数组中不重复元素个数

方法一

const getRandomArr = function (arr, n) {
  const result = [];
  while (result.length < n) {
    // 生成随机数
    const randomNum = arr[Math.floor(Math.random() * arr.length)];
    if (!result.includes(randomNum)) {
      result.push(randomNum);
    }
  }
  return result;
};

getRandomArr([1,2,3,4,5,6,7], 3); // [5, 3, 1]
getRandomArr([1,2,3,4,5,6,7], 4); // [1, 3, 5, 6]
getRandomArr([1,2,3,4,5,6,7], 2); // [7, 4]

时间复杂度:O(n2)

方法二

通过map判断是否重复,降低时间复杂度

const getRandomArr2 = function (arr, n) {
  const result = [];
  const map = new Map();
  while (result.length < n) {
    // 生成随机数
    const randomNum = arr[Math.floor(Math.random() * arr.length)];
    if (!map.has(randomNum)) {
      map.set(randomNum, randomNum);
      result.push(randomNum);
    }
  }
  return result;
};

时间复杂度:O(n)