Java O(n) variant of reservoir sampling


  • 0
    D
    public class Solution {
        
        private int[] nums;
    
        public Solution(int[] nums) {
            this.nums = nums;
        }
        
        private Random r = new Random();
        
        public int pick(int target) {
            int ret = -1;
            if (nums == null) {
                return ret;
            }
            int upbound = 1;
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == target) {
                    if (r.nextInt(upbound) == 0) {
                        ret = i;
                    } 
                    upbound++;
                }
            }
            return ret;
        }
    }
    

Log in to reply
 

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