398. Random Pick Index

随机返还target值的坐标(如果存在多个target).

不太明白为什么这个题是M难度的。

无非是要么弄TABLE之类的,开始麻烦点,但是pick的时候直接PICK出来就行了。
要么开始简单点,都存了,选的时候再随机选。

前者各种溢出。。貌似memory在leetcode比较值钱。。就用后者

public class Solution 
{
    int[] nums;
    public Solution(int[] nums) 
    {
        this.nums = nums;
    }
    
    public int pick(int target) 
    {
        int i = 0;
        while(nums[i] != target) i++;
        int start = i;
        while(i < nums.length && nums[i] == target) i++;
        Random rdm = new Random();
        
        
        return start + rdm.nextInt(i-start);
    }
}

有一种思路挺逗的:

public class Solution {
    int[] nums;
    Random r;
    public Solution(int[] nums) {
        this.nums = nums;
        r = new Random();
    }
    
    public int pick(int target) {
        int size = nums.length;
        int i = r.nextInt(size);
        while (nums[i] != target) {
            i = r.nextInt(size);
        }
        
        return i;
    }
}

无限随机选,选到为止。。。这样确实概率是一样的,不过总觉得很奇怪的样子。。。

原文地址:https://www.cnblogs.com/reboot329/p/5868202.html