题解 | #无重复数组#

无重复数组

http://www.nowcoder.com/practice/d2fa3632268b41df9bc417b74802ad8c

思路

  1. 生成一个两数之间的整数,使用到Math的random函数

random

random()会返回一个浮点型伪随机数字,范围[0, 1)

  • 返回一个两数之间的 随机数 ,范围在[start, end)
Math.random()*(end - start)
  • 返回一个两数之间的 整数 ,范围在[start, end)
// floor向下取整
Math.floor(Math.random()*(end - start))
  • 返回一个两数之间的 整数 ,范围在[start, end]
Math.floor(Math.random()*(end - start+1)) + start

此题中要求的是第三种情况

代码

 			const _getUniqueNums = (start,end,n) => {
                // 补全代码
                const res = []
                while(res.length < n) {
                  let num = Math.floor(Math.random()*(end-start+1))+start
                  // 不能有重复的元素
                  if (!res.includes(num)) {
                    res.push(num)
                  }
                }
                return res
            }
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 13:05
TMD找工作本来就烦,这东西什么素质啊😡
Beeee0927:hr是超雄了,不过也是有道理的
点赞 评论 收藏
分享
06-19 19:06
门头沟学院 Java
码农索隆:别去东软,真学不到东西,真事
点赞 评论 收藏
分享
评论
8
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务