Simple Java Solution


  • 0
    J
    public class Solution {
        
        HashMap<Integer,List<Integer>> hmap;
        public Solution(int[] nums) {
            hmap = new HashMap<Integer,List<Integer>>();
            
            for(int i=0;i<nums.length;i++)
            {
                List<Integer> tempList;
                if(hmap.containsKey(nums[i]))
                    tempList=hmap.get(nums[i]);
                else
                    tempList=new ArrayList<Integer>();
                
                tempList.add(i);
                hmap.put(nums[i],tempList);
            }
        }
        
        public int pick(int target) {
            
            List<Integer> tempList=hmap.get(target);
            int index= (int)(Math.random()*tempList.size());
            return tempList.get(index);
            
        }
    }
    

Log in to reply
 

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