LeetCode 398 Random Pick Index

Tag: 数学类题目 LeetCode Posted on 2022-03-01 11:17:22 Edited on 2022-03-01 11:17:22 Views: 164

概述

https://leetcode.com/problems/random-pick-index/

暴力解

遍历数组,将每个 target 对应的 idx 存入哈希表。

class Solution {
public:
    unordered_map<int, vector<int>> m;
    Solution(vector<int>& nums) {
        for (int i = 0; i < nums.size(); i++) m[nums[i]].push_back(i);
    }
    
    int pick(int target) {
        int r = rand() % m[target].size();
        return m[target][r];
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/