leetcode710黑名单中的随机数

题目地址

https://leetcode-cn.com/problems/random-pick-with-blacklist/

题目描述

给定一个包含 [0,n ) 中独特的整数的黑名单 B,写一个函数从 [ 0,n ) 中返回一个不在 B 中的随机整数。
对它进行优化使其尽量少调用系统方法 Math.random() 。
提示:
    1 <= N <= 1000000000
    0 <= B.length < min(100000, N)
    [0, N) 不包含 N,详细参见 interval notation 。

示例 1:
输入: 
["Solution","pick","pick","pick"]
[[1,[]],[],[],[]]
输出: [null,0,0,0]

示例 2:
输入: 
["Solution","pick","pick","pick"]
[[2,[]],[],[],[]]
输出: [null,1,1,1]

示例 3:
输入: 
["Solution","pick","pick","pick"]
[[3,[1]],[],[],[]]
Output: [null,0,0,2]

示例 4:
输入: 
["Solution","pick","pick","pick"]
[[4,[2]],[],[],[]]
输出: [null,1,3,1]

输入语法说明:
输入是两个列表:调用成员函数名和调用的参数。Solution的构造函数有两个参数,N 和黑名单 B。pick 没有参数,输入参数是一个列表,即使参数为空,也会输入一个 [] 空列表。

代码实现

javascript

/**
 * @param {number} N
 * @param {number[]} blacklist
 */
var Solution = function(N, blacklist) {
    this.map = {};
    this.N = N;
    this.blacklist = blacklist;
    for (let i of blacklist) {
        this.map[i] = 11; // 确保blacklist中的元素都在this.map中,可以赋值11以外的任何数,不能为undefined和null
    }

    let len = N - blacklist.length, last = N-1;
    for (let i of blacklist) {
        // 将索引len之前的blacklist中元素与len之后的非blacklist中元素建立映射
        if (i >= len) continue; 
        while (this.map[last] !== undefined) last--;
        this.map[i] = last;
        last--;
    }
};

/**
 * @return {number}
 */
Solution.prototype.pick = function() {
    let index = parseInt(Math.random()*(this.N - this.blacklist.length));
    if (this.map[index] !== undefined) return this.map[index]; // 如果index为blacklist中元素,则返回其映射数
    return index;
};

/**
 * Your Solution object will be instantiated and called as such:
 * var obj = new Solution(N, blacklist)
 * var param_1 = obj.pick()
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值