simple java solution o(n)


  • 0
    M
    public class Solution {
        static int[] nums; 
    
        public Solution(int[] nums) {
            this.nums=nums;
        }
        
        public int pick(int target) {
            
            List<Integer> mm = new ArrayList<Integer>();
        	
        	for(int i=0; i<nums.length; i++){
        		if(nums[i]==target)
        			mm.add(i);
        	}
        	Random rn=new Random();
        	return mm.get(rn.nextInt(mm.size()));
        }
    }
    

Log in to reply
 

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