题目
给定一个数组,及一个长度n,生成长度为n的不重复随机数组,n不大于数组中不重复元素个数
方法一
const getRandomArr = function (arr, n) {
const...result = [];
while (result.length < n) {
// 生成随机数
const randomNum = arr[Math.floor(Math.random...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判断是否重复...function (arr, n) {
const result = [];
const map = new Map();
while (result.length < n) {
// 生成随机数