My easy and simple solution beating 99.53%


  • 2
    public class Solution {
        int[] nums;
        Random myrand;
        public Solution(int[] nums) {
            this.nums = nums;
            myrand = new Random();
        }
        public int pick(int target) {
            int count = 0;
            int ret = -1;
            for(int i=0;i<nums.length;i++){
                if(nums[i]==target){
                    count++;
                    ret = myrand.nextInt(count)==0?i:ret;
                }
            }
            return ret;
        }
    }
    

  • 0
    S

    should we place break in if condition because ret is getting updated all time


Log in to reply
 

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