其他分享
首页 > 其他分享> > 398. Random Pick Index

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;
    }
}

标签:count,Index,nums,int,Random,Solution,398,public
来源: https://www.cnblogs.com/feiflytech/p/15934382.html