398. 随机数索引

 

labuladong 题解思路
难度中等

给你一个可能含有 重复元素 的整数数组 nums ,请你随机输出给定的目标数字 target 的索引。你可以假设给定的数字一定存在于数组中。

实现 Solution 类:

  • Solution(int[] nums) 用数组 nums 初始化对象。
  • int pick(int target) 从 nums 中选出一个满足 nums[i] == target 的随机索引 i 。如果存在多个有效的索引,则每个索引的返回概率应当相等。

 

 

 

import copy
class Solution:

    def __init__(self, nums: List[int]):
        self.org = nums
        self.rand = copy.deepcopy(nums)


    def reset(self) -> List[int]:
        return self.org


    def shuffle(self) -> List[int]:
        for i in range(len(self.rand)):
            p = random.randint(0,i)
            self.rand[p], self.rand[i] = self.rand[i],self.rand[p]
        return self.rand



# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()

 

 

 

 

 

 

class Solution {
public:
    unordered_map<int, vector<int>> index_map;
    Solution(vector<int>& nums) {
        for(int i = 0; i < nums.size();i++) {
            index_map[nums[i]].emplace_back(i);
        }

    }
    int pick(int target) {
        vector<int> index_list = index_map[target];
        return index_list[rand() % index_list.size()];

    }
};

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

 

 

 

 

蓄水池会超时

 

class Solution {
    vector<int> &nums;
public:
    Solution(vector<int> &nums) : nums(nums) {}

    int pick(int target) {
        int ans;
        int cnt = 0;
        for (int i = 0;i < nums.size(); ++i) {
            if (nums[i] == target) {
                ++cnt; // 第 cnt 次遇到 target
                if (rand() % cnt == 0) {
                    ans = i;
                }
            }
        }
        return ans;
    }
};

 

posted @ 2022-08-24 23:18  乐乐章  阅读(10)  评论(0编辑  收藏  举报