首页 > 代码库 > Majority Element II
Majority Element II
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋
times. The algorithm should run in linear time and in O(1) space.
Hint:
- How many majority elements could it possibly have?
- Do you have a better hint? Suggest it!
class Solution {public: vector<int> majorityElement(vector<int>& nums) { vector<int> res; int m = 0, n = 0, cm = 0, cn = 0; for (size_t i = 0; i < nums.size(); i++) { if (nums[i] == m) cm++; else if (nums[i] == n) cn++; else if (cm == 0) { m = nums[i]; cm++; } else if (cn == 0) { n = nums[i]; cn++; } else { cn--; cm--; } } cm = 0; cn = 0; for (auto num : nums) { if (num == m) { cm++; } else if (num == n) { cn++; } } if (cm > nums.size() / 3) res.push_back(m); if (cn > nums.size() / 3) res.push_back(n); return res; }};
Majority Element II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。