Simple JAVA solution with HashMap


  • 0
    B
    public class Solution {
        HashMap<Integer, ArrayList<Integer>> hm;
        public Solution(int[] nums) {
            hm = new HashMap();
            for(int i = 0; i < nums.length; i++) {
                if(hm.get(nums[i]) != null) hm.get(nums[i]).add(i);
                else {
                    ArrayList<Integer> cur = new ArrayList();
                    cur.add(i);
                    hm.put(nums[i], cur);
                }
            }
        }
        
        public int pick(int target) {
            int range = hm.get(target).size();
            return hm.get(target).get((int)(Math.random() * range));
        }
    }
    /**
     * 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.