270ms beats 97.68%


  • 0
    I
    public class Solution {
        private final int[] nums;
        private final Map<Integer, List<Integer>> map;    
        private final Random random;
        
        public Solution(int[] nums) {
            this.nums = nums;
            map = new HashMap<>();
            random = new Random();
        }
        
        public int pick(int target) {
            if(!map.containsKey(target)) {
                map.put(target, new ArrayList<>());
                
                for(int i=0; i<nums.length; i++) {
                    if(nums[i] == target) {
                        map.get(target).add(i);
                    }
                }
            }
            
            final List<Integer> indices = map.get(target);
            return indices.get(random.nextInt(indices.size()));
        }
    }
    

Log in to reply
 

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