[LeetCode] Majority Element II
Posted immjc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] Majority Element II相关的知识,希望对你有一定的参考价值。
Given an integer array of size n, find all elements that appear more than ? n/3 ?
times.
Note: The algorithm should run in linear time and in O(1) space.
Example 1:
Input: [3,2,3] Output: [3]
Example 2:
Input: [1,1,1,3,3,2,2,2] Output: [1,2]
n/3 times说明这样的数至多存在2个。
所以使用两个数n1,n2表示候选的数字,c1,c2表示这两个数出现的次数。
遍历数组,记当前数组为num,如果num与n1,n2其一相等,则对应的c1或c2加一。
如果num与n1和n2都不等,此时如果c1或c2其一为0,则令对应的候选数为num,并令其加一,
否则c1和c2各自减一,
最后再统计一次候选数字出现的次数是否大于n/3
class Solution { public: vector<int> majorityElement(vector<int>& nums) { vector<int> res; if (nums.empty()) return res; int n1 = nums[0], n2 = 0; int c1 = 1, c2 = 0; for (int i = 1; i < nums.size(); ++i) { if (nums[i] == n1) c1++; else if (nums[i] == n2) c2++; else { if (c1 == 0) { n1 = nums[i]; c1 = 1; } else if (c2 == 0) { n2 = nums[i]; c2 = 1; } else { c1--; c2--; } } } c1 = 0, c2 = 0; for (auto& num : nums) { if (num == n1) c1++; else if (num == n2) c2++; } if (c1 > nums.size() / 3) res.push_back(n1); if (c2 > nums.size() / 3 && n1 != n2) res.push_back(n2); return res; } }; // 12 ms
以上是关于[LeetCode] Majority Element II的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 169. Majority Element