Random Pick Index Java Solution


  • 0
    T
    class Solution {
        int[] arr;
        public Solution(int[] nums) {
            this.arr = nums;
        }
        public int pick(int target) {
            int count = 0;
            int result = -1;
            for (int i = 0;i<this.arr.length;i++){
                if (target == this.arr[i]){
                    count++;
                    Random rand = new Random(); 
                    int r = rand.nextInt(count);
                    if (r==count -1){
                        result = i;
                    }      
                }
            }
            return result;
        }
    }
    

Log in to reply
 

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