398. Random Pick Index

The following is my solution, which is easy to understand:

class Solution {
    Map<Integer,List<Integer>> map = new HashMap<>();
    Random r = new Random();
    public Solution(int[] nums) {
        for(int i=0;i<nums.length;i++){
            map.putIfAbsent(nums[i], new ArrayList<>());
            map.get(nums[i]).add(i);
        }
    }
    
    public int pick(int target) {
        List<Integer> index = map.get(target);
        int randomIndex = r.nextInt(index.size());
        return index.get(randomIndex);
    }
}

The following is the other solution, but not very easy to understand:

class Solution {
    private int[] nums;
    private Random r = new Random();

    public Solution(int[] nums) {
        this.nums = nums;
    }

    public int pick(int target) {
        int res = 0;
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target){
                count++;
                if(r.nextInt(count) == count-1)
                    res = i;  
            } 
        }
        return res;
    }
}
上一篇:【Example】C++ 虚基类与虚继承 (菱形继承问题)


下一篇:Scala刮:使用Intellij IDEA写hello world