给定一个数组,及一个长度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)
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。