398.隨機數索引
阿新 • • 發佈:2018-11-14
給定一個可能含有重複元素的整數陣列,要求隨機輸出給定的數字的索引。 您可以假設給定的數字一定存在於陣列中。
注意:
陣列大小可能非常大。 使用太多額外空間的解決方案將不會通過測試。
示例:
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);
class Solution {
public:
Solution(vector<int> nums): v(nums) {}
int pick(int target) {
int cnt = 0, res = -1;
for (int i = 0; i < v.size(); ++i) {
if (v[i] != target) continue;
++cnt;
if (rand() % cnt == 0) res = i;
}
return res;
}
private:
vector<int> v;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/