标签:div ++ problem 空间 public tor lse html ble
给定一个大小为 n 的数组,找出其中所有出现超过 ? n/3 ? 次的元素。 你的算法应该在O(1)空间中以线性时间运行。
详见:https://leetcode.com/problems/majority-element-ii/description/
摩尔投票法 Moore Voting
class Solution { public: vector<int> majorityElement(vector<int>& nums) { vector<int> res; int m = 0, n = 0, cm = 0, cn = 0; for (auto &a : nums) { if (a == m) { ++cm; } else if (a ==n) { ++cn; } else if (cm == 0) { m = a, cm = 1; } else if (cn == 0) { n = a, cn = 1; } else { --cm, --cn; } } cm = cn = 0; for (auto &a : nums) { if (a == m) { ++cm; } else if (a == n) { ++cn; } } if (cm > nums.size() / 3) { res.push_back(m); } if (cn > nums.size() / 3) { res.push_back(n); } return res; } };
参考:https://www.cnblogs.com/grandyang/p/4606822.html
229 Majority Element II 求众数 II
标签:div ++ problem 空间 public tor lse html ble
原文地址:https://www.cnblogs.com/xidian2014/p/8758768.html