398. Random Pick Index 题解

来源:互联网 发布:淘宝优惠券图片怎么做 编辑:程序博客网 时间:2024/05/18 16:15

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


题目链接:398. Random Pick Index



算法描述:


        由题意知,给定一个包含一串整数的数组,数组中的各个元素可能会有重复,给定一个目标值 “Target”,我们将随机返回一个数组中元素值等于该目标值的元素索引。


     我们直接对该数组进行遍历,当发现与目标值相等的元素时,我们将这个元素的索引放入一个容器中,遍历完成之后,该容器存放了所有满足要求的元素索引。最后,我们用随机数生成器 “rand()” 产生的随机数在容器中取出一个索引即可。


     代码中 “rand() % stack0.size()” 保证了产生随机数的范围在容器的大小之内。


代码:

class Solution {public:    vector<int> nums2;    vector<int> stack0;    Solution(vector<int> nums) {        nums2=nums;    }        int pick(int target) {        if(nums2.size()==0){            return 0;        }        for(int i=0; i<nums2.size(); i++){            if(nums2[i]==target){                stack0.push_back(i);            }        }        int ans_index=rand()%stack0.size();        return stack0[ans_index];    }};/** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(nums); * int param_1 = obj.pick(target); */




0 0