题解 | #简洁优雅高效O(n)#

无重复数组

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

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

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年
点赞 评论 收藏
分享
兄弟们,实习都是在接各种api,该怎么包装简历
仁者伍敌:感觉我自己做小项目也是各种api啊,我要怎么包装简历
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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