题解 | #无重复数组#

无重复数组

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

1.  时间复杂度为O(n)
2. 生成range(start, end)的数组 
3. 随机数生成函数 
4. 将随机数选中的位置与数组末尾交换,提高效率 。交换操作时间复杂度为O(1)

const _getUniqueNums = (start, end, n) => {
    // 补全代码
    const arr = Array.from(new Array(end - start + 1), (v, i) => start + i);
    const randIndex = (max) => Math.floor(Math.random() * max);
    const ans = [];
    for (let j = 0; j < n; j++) {
        let selected = randIndex(arr.length - j);
        ans.push(arr[selected]);
        [arr[arr.length - 1 - j], arr[selected]] = [arr[selected], arr[arr.length - 1 - j]];
    }
    return ans;
}


全部评论

相关推荐

在春招的哈士奇很苦闷:这个社会求职终于颠成了我不认识的样子
点赞 评论 收藏
分享
程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

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