share my java solution! beat 98%!


  • 0
    C
    public class Solution {
        int[] nums;
        Random random;
        public Solution(int[] nums) {
            this.nums=nums;
            random=new Random();
        }
        
        public int pick(int target) {
            int index=0;
            int r=0;
            while(nums[index]!=target){
                index++;
            }
              
            r=index++;
            int i=0;
            
            while(index!=nums.length&&index<nums.length){
                
                if(nums[index]!=target){
                    index++;
                    continue;
                }
                
                if(index!=nums.length){
                    i++;
                    int randomnum=random.nextInt(i+1);
                    if(randomnum==i){
                        r=index;
                    }
                    index++;
                }
            }
            return r;
        }
    }
    
    

Log in to reply
 

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