LeetCode-Random Pick Index

LiBlog發表於2016-09-12

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.

Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.

Example:

int[] nums = new int[] {1,2,3,3,3}; Solution solution = new Solution(nums); // pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(3); // pick(1) should return 0. Since in the array only nums[0] is equal to 1. solution.pick(1);

Analysis:

Get from here:

https://discuss.leetcode.com/topic/58322/what-on-earth-is-meant-by-too-much-memory/6

Quote:

Hi, the question is the same with Q382 Linked List Random Node, the only difference is in this question, we only count the target, and get the random index from the target indices.

The background of the question is the data stream is very large, and we only need one target index from one data stream, the next data stream is another one, so why do we store every data stream, we just need O(1) space and O(n) time to traverse the first data stream , and O(1) space and O(n) time to traverse the second data stream....

Have a look at the other guy's solution, it's the same with my explanation:
https://discuss.leetcode.com/topic/58301/simple-reservoir-sampling-solution

Solution:

public class Solution {
    int[] numList;
    Random engine = new Random();

    public Solution(int[] nums) {
        numList = nums;
    }
    
    public int pick(int target) {
        int count = 0;
        int index = -1;
        for (int i=0;i<numList.length;i++)
            if (numList[i] == target){
                count++;
                int val = engine.nextInt(count);
                if (val==0){
                    index = i;
                }
            }
        return index;
    }
}

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

 

相關文章