1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
majority-element-ii.cpp 1.50 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 10年前 . Update majority-element-ii.cpp
// Time: O(n)
// Space: O(1)
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int k = 3;
const int n = nums.size();
unordered_map<int, int> hash;
for (const auto& i : nums) {
++hash[i];
// Detecting k items in hash, at least one of them must have exactly
// one in it. We will discard those k items by one for each.
// This action keeps the same mojority numbers in the remaining numbers.
// Because if x / n > 1 / k is true, then (x - 1) / (n - k) > 1 / k is also true.
if (hash.size() == k) {
auto it = hash.begin();
while (it != hash.end()) {
if (--(it->second) == 0) {
hash.erase(it++);
} else {
++it;
}
}
}
}
// Resets hash for the following counting.
for (auto& it : hash) {
it.second = 0;
}
// Counts the occurrence of each candidate integer.
for (const auto& i : nums) {
auto it = hash.find(i);
if (it != hash.end()) {
++it->second;
}
}
// Selects the integer which occurs > [n / k] times.
vector<int> ret;
for (const pair<int, int>& it : hash) {
if (it.second > n / k) {
ret.emplace_back(it.first);
}
}
return ret;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助