[leetcode]Random Pick Index

作者:luozhipeng   发表日期:2016-9-17  浏览:793次

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 {
    vector<int> nums;
    
public:
    Solution(vector<int> nums) {
        this->nums = nums;
        srand(time(NULL));
    }
    
    int pick(int target) {
        int count = 1, len = nums.size(), ans = -1;
        for(int i = 0; i < len; ++i)
        {
            if(nums[i] != target)
                continue;
            
            if(rand()%count++ == 0)
                ans = i;
        }
        return ans;
    }
};

标签:

本文固定链接: http://www.luozhipeng.com/?p=1160
转载请注明: luozhipeng 2016-9-17 于 罗志鹏的BLOG 发表

上一篇: :下一篇
评论:请安装多说插件!
返回顶部