题解 | #无重复数组#

无重复数组

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 评论
分享
牛客网
牛客企业服务