Simple java HashMap method


  • 0
    P
    import java.util.Random;
    public class Solution {
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        Random random;
        int[] nums;
        public Solution(int[] nums) {
            this.nums = nums;
            for(int i = 0;i<nums.length;i++)
            {
                if(!map.containsKey(nums[i]))
                {
                    map.put(nums[i],1);
                }
                else
                {
                    map.put(nums[i],map.get(nums[i])+1);
                }
            }
            random = new Random();
        }
        
        public int pick(int target) {
            int targetNumber = random.nextInt(map.get(target))+1;
            int count = 0;
            for(int i = 0;i<nums.length;i++)
            {
                if(nums[i] == target)
                {
                    count++;
                    if(count == targetNumber)
                    {
                        return i;
                    }
                }
            }
            return 0;
        }
    }
    
    /**
     * 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.