题目

给定一个可能含有重复元素的整数数组,要求随机输出给定的数字的索引。 您可以假设给定的数字一定存在于数组中。

注意:
数组大小可能非常大。 使用太多额外空间的解决方案将不会通过测试。

示例:

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

// pick(3) 应该返回索引 2,3 或者 4。每个索引的返回概率应该相等。
solution.pick(3);

// pick(1) 应该返回 0。因为只有nums[0]等于1。
solution.pick(1);

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/random-pick-index
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

基本类似382题,不同的是,只需要在遍历到target时才计数,其余数不用管。然后随机生成一个[0,cnt)之间的数,如果为0,将ans设为当前下标。

代码

  1. class Solution {
  2. int[] nums;
  3. Random random;
  4. public Solution(int[] nums) {
  5. this.nums = nums;
  6. random = new Random();
  7. }
  8. public int pick(int target) {
  9. int n = nums.length;
  10. int cnt = 0;
  11. int ans = 0;
  12. for (int i = 0; i < n; i++) {
  13. if (nums[i] == target) {
  14. cnt++;
  15. int num = random.nextInt(cnt);
  16. if (num == 0) {
  17. ans = i;
  18. }
  19. }
  20. }
  21. return ans;
  22. }
  23. }
  24. /**
  25. * Your Solution object will be instantiated and called as such:
  26. * Solution obj = new Solution(nums);
  27. * int param_1 = obj.pick(target);
  28. */