My Java Reservoir Sampling Solution


  • 0
    F
    private int[] nums;
    private Random r = new Random();
    
    public RandomPickIndex(int[] nums) {
    	this.nums = nums;
    }
    
    public int pick(int target) {
    	int res = -1;
    	int n = 1;
    	for (int i = 0; i < nums.length; i++) {
    		if (nums[i] == target) {
    			if (r.nextInt(n++) == 0) {
    				res = i;
    			}
    		}
    	}
    	return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.