LeetCode 随机数索引

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

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

示例:

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

方法一:暴力法。使用map将num与出现的所有下标构成的集合关联。

class Solution {
private:
	map<int, vector<int> > myMap;//myMap[num]用于记录num出现的各个下标
public:
	Solution(vector<int> nums) {
		int numsSize = nums.size();
		//统计各种元素出现的下标
		for (int index = 0; index < numsSize; ++index) {
			myMap[nums[index]].push_back(index);
		}
	}

	int pick(int target) {
		int randomNum = rand() % myMap[target].size();//获取target下标集合中的随机一个
		return myMap[target][randomNum];
	}
};
/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int param_1 = obj.pick(target);
 */

在这里插入图片描述
从执行效果来看,时间、空间都有很大的消耗。在这里插入图片描述
对上面的蛮力法,进行小小的优化,将统计所有的出现下标修改为动态统计。

class Solution {
public:
    vector<int> copy;
    Solution(vector<int> nums) {
        copy = nums;
    }    
    int pick(int target) {
        int copySize = copy.size();
        vector<int> targetIndex;//用于记录target出现的下标集合
        //统计target所有出现的下标
        for(int index = 0; index < copySize; ++index){
            if(copy[index]==target) {
                targetIndex.push_back(index);
            }
        }
        //然后取出随机的一个下标
        return targetIndex[rand() % targetIndex.size()];
    }
};

在这里插入图片描述
下面是76ms的示范代码,不过一行注释都没有。。。
评论区说是什么“水塘抽样”啥的,但是没有人具体的解释。

class Solution {
public:
    vector<int> copy;
    Solution(vector<int> nums) {
        copy = nums;
    }    
    int pick(int target) {
        int result = 0;
        for(int i = 0, cnt = 1; i < copy.size(); ++i){
            if(copy[i]==target && rand()%(cnt++)==0) {
                result = i;
            }
        }
        return result;
    }
};

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

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41855420/article/details/88640181