LeetCode 398 Random Pick Index(蓄水池抽樣典型例題)

Tech In Pieces發表於2020-12-10

Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.

就是說 給出一個array, 裡面有Integers,可以帶有重複。現在我們給定一個target,讓隨機輸出array裡面值等於target的元素對應的target.當然,如果只有這一個值等於target的元素的話,就直接返回這個index,但是如果有多個的話 就隨機返回一個。
要注意,我們保證一定存在這個target.
同時也要注意:array的size可能很大 在解題過程中不要用太多的額外空間。

class Solution {

    public Solution(int[] nums) {
        
    }
    
    public int pick(int target) {
        
    }
}

idea:
the initial idea will be just get all the value and it’s index, and we are gonna randomly pick one of them.
so we can choose HashMap<Integer, List< Integer >> map: key: value value: list of indexes.

but array.size() maybe huge and the new hashmap will take too much space.
so can we don’t do any preprocess, and each time we pick it, we iterate num and get all the indexes and randomly get one from them.
but there comes another thing: the size of this array is large, and since we gonna use pick() for many times, so that will be bad in time complexity too.
Actually, after saw the solution, I realized that it is a reservoir sampling

class Solution {
    
    int[] nums;
    Random rand;
    int N;

    public Solution(int[] nums) {
        this.nums = nums; //同名的一定要用nums不然會出現null pointer的錯誤
        N = nums.length;
        rand = new Random();
    }
    
    public int pick(int target) {
        int count = 0;
        int res = 0;
        for (int i = 0; i < N; i++) {
            if (nums[i] != target) {
                continue;
            } else {
                count++;
                int random = rand.nextInt() % count;
                if (random == 0) {
                    res = i;
                }
            }
        }
        return res;
        
    }
}

相關文章