398. Random Pick Index随机pick函数

[抄题]:

Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.

Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.

Example:

int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);

// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);

// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

[一句话思路]:

Random是一个,要拿来新建对象

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 如果nums[i]不是target,就用continue继续

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

  1. 需要新建对象 this.rand = new Random();

[复杂度]:Time complexity: O() Space complexity: O()

[英文数据结构或算法,为什么不用别的数据结构或算法]:

rnd.nextInt(n) 

在方法调用返回介于0(含)和n(不含)伪随机,均匀分布的int值,所以括号内的参数必须 >0

[算法思想:递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

class Solution {
    int[] nums;
    Random rand;
        
    public Solution(int[] nums) {
        this.nums = nums;
        this.rand = new Random();
    }
    
    public int pick(int target) {
        //ini: res, 
        int res = -1, count = 0;
        
        //for loop, find or not
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != target) continue;
            if (rand.nextInt(++count) == 0) res = i;
        }
        
        //return
        return res;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int param_1 = obj.pick(target);
 */
View Code

 

posted @ 2018-05-16 11:13  苗妙苗  阅读(310)  评论(0编辑  收藏  举报