前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在指定数据源里面生成一个长度为 n 的不重复随机数组

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

作者头像
玖柒的小窝
修改2021-11-04 09:20:55
8710
修改2021-11-04 09:20:55
举报
文章被收录于专栏:各类技术文章~

题目

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

方法一

代码语言:javascript
复制
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判断是否重复,降低时间复杂度

代码语言:javascript
复制
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 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 方法一
  • 方法二
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档