1. 程式人生 > >710. Random Pick with Blacklist - LeetCode

710. Random Pick with Blacklist - LeetCode

.get contains nta class ems 技術 length 隨機數 範圍

Question

710. Random Pick with Blacklist

技術分享圖片

Solution

題目大意:給一個N,表示一個範圍[0,N),給一個黑名單列表blacklist,其中blacklist中的元素在[0,N)範圍內,調用pick方法的時候隨機返回一個數,這個數滿足

  1. 在[0,N)範圍
  2. 不在blacklist內
  3. 要隨機

思路:構造一個集合M,該M是 [0,N) - blacklist 的一個集合,調用pick時,返回[0,M)的一個隨機數並根據這個隨機數從集合M中取數即可。

Java實現:

class Solution {
    int M;
    Map<Integer, Integer> map;
    Random r;
    public Solution(int N, int[] blacklist) {
        M = N - blacklist.length;
        map = new HashMap<>();
        r = new Random();
        for (int tmp : blacklist) {
            map.put(tmp, -1);
        }
        
        for (int tmp : blacklist) {
            if (tmp < M) {
                while (map.containsKey(N-1)) {
                    N--;
                }
                map.put(tmp, --N);
            }
        }
    }

    public int pick() {
        // random in [0,N) not in blacklist
        int p = r.nextInt(M);
        if (map.containsKey(p)) return map.get(p);
        return p;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(N, blacklist);
 * int param_1 = obj.pick();
 */

710. Random Pick with Blacklist - LeetCode