Simple AC java solution using Hashmap.


  • 0
    Y
    
    public class Solution {
            HashMap<Integer, ArrayList<Integer>> map;
        public Solution(int[] nums) {
            map = new HashMap<Integer, ArrayList<Integer>>();
            for(int i=0;i<nums.length;i++)
            {
                if(!map.containsKey(nums[i]))
                
                {
                    map.put(nums[i],new ArrayList<Integer>());
                }
                map.get(nums[i]).add(i);
            }
        }
        
        public int pick(int target) {
            int count=map.get(target).size();
            //generate a random integer from 0 to count-1.
            int index=0+(int)(Math.random()*(count-1-0+1));
            return map.get(target).get(index);
            
        }
    }
    
    /**
     * Your Solution object will be instantiated and called as such:
     * Solution obj = new Solution(nums);
     * int param_1 = obj.pick(target);
     */
    
    

Log in to reply
 

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