app开发者平台在数字化时代的重要性与发展趋势解析
634
2022-10-09
398. Random Pick Index
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);
思路: 给了一个数组,包含若干数,可能有重复,然后再给一个数,查找其位置,如果这个数在数组中只出现了一次就返回那个位置,如果不止一次就随机返回一个。
class Solution { private int[] nums; private Random random; public Solution(int[] nums) { this.nums = nums; this.random = new Random(); } public int pick(int target) { int result = -1; int upbound = 1; for (int i = 0; i < nums.length; i++) { if (nums[i] == target) { if (random.nextInt(upbound) == 0) { result = i; } upbound++; } } return result; }}/** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(nums); * int param_1 = obj.pick(target); */
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~