Different Idea in JAVA, without random.nextInt(size), just use Math.random.


  • 0
    N

    '''
    public class Solution {

    Map<Integer, List<Integer>> maps;
    public Solution(int[] nums) {
        maps = new HashMap<>();
        for(int i=0; i<nums.length; i++){
            List<Integer> tmp = new ArrayList<>();
            if(maps.containsKey(nums[i])){
                tmp = maps.get(nums[i]);
            }
            tmp.add(i);
            maps.put(nums[i], tmp);
        }
    }
    
    public int pick(int target) {
        if(maps.containsKey(target)){
            List<Integer> l = maps.get(target);
            double equalPro = (double)1/l.size();
            double randomNum = Math.random();
            return l.get((int)(randomNum/equalPro));
            
        }else{
            return 0;
        }
    }
    

    }

    '''


Log in to reply
 

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