Every day a Leetcode
题目来源:3092. 最高频率的 ID
解法1:哈希 + 有序集合
用哈希表 cnt 记录 x=nums[i] 的出现次数 cnt[x](用 freq 更新出现次数)。
用有序集合 multiset 记录 cnt[x],从而可以 O(logn) 知道最大的 cnt[x] 是多少。
代码:
/*
* @lc app=leetcode.cn id=3092 lang=cpp
*
* [3092] 最高频率的 ID
*/
// @lc code=start
class Solution
{
public:
vector<long long> mostFrequentIDs(vector<int> &nums, vector<int> &freq)
{
int n = nums.size();
unordered_map<int, long long> cnt;
multiset<long long> ms;
vector<long long> ans(n);
for (int i = 0; i < n; i++)
{
auto it = ms.find(cnt[nums[i]]);
if (it != ms.end())
ms.erase(it);
cnt[nums[i]] += freq[i];
ms.insert(cnt[nums[i]]);
ans[i] = *(ms.rbegin());
}
return ans;
}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O(nlogn),其中 n 是数组 nums 的长度。
空间复杂度:O(n),其中 n 是数组 nums 的长度。
解法2:哈希 + 懒删除堆
也可以不用有序集合,而是用一个最大堆保存数对 (cnt[x],x)。
在堆中查询 cnt[x] 的最大值时,如果堆顶保存的数据并不是目前实际的 cnt[x],那么就弹出堆顶。
代码:
/*
* @lc app=leetcode.cn id=3092 lang=cpp
*
* [3092] 最高频率的 ID
*/
// @lc code=start
// 哈希 + 懒删除堆
class Solution
{
public:
vector<long long> mostFrequentIDs(vector<int> &nums, vector<int> &freq)
{
int n = nums.size();
unordered_map<int, long long> cnt;
priority_queue<pair<long long, int>> pq;
vector<long long> ans(n);
for (int i = 0; i < n; i++)
{
int x = nums[i];
cnt[x] += freq[i];
pq.push(make_pair(cnt[x], x));
// 堆顶保存的数据已经发生变化,删除
while (pq.top().first != cnt[pq.top().second])
pq.pop();
ans[i] = pq.top().first;
}
return ans;
}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O(nlogn),其中 n 是数组 nums 的长度。
空间复杂度:O(n),其中 n 是数组 nums 的长度。