My beautiful solution Good for Datastructer


  • 0
    W
    public class Solution {
        HashMap<Integer, List<Integer>> num2poslist;
        public Solution(int[] nums) {
            num2poslist = new HashMap<>();
            for(int i = 0; i < nums.length; i++) {
                if(num2poslist.containsKey(nums[i])) {
                    List<Integer> list = num2poslist.get(nums[i]);
                    list.add(i);
                    num2poslist.put(nums[i], list);
                } else {
                    List<Integer> list = new ArrayList<>();
                    list.add(i);
                    num2poslist.put(nums[i], list);
                }
            }
        }
        
        public int pick(int target) {
            List<Integer> list = num2poslist.get(target);
            Random ran = new Random();
            int index = ran.nextInt(list.size());
            return list.get(index);
        }
    }
    

Log in to reply
 

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