[LeetCode] Majority Element II
Given an integer array of size n, find all elements that appear more⌊ n/3 ⌋Times. The algorithm shocould run in linear time and in O (1) space.
Solutions
Moore's voting method. The core of the voting method is to find two candidate modes for voting. It needs to be traversed twice. The first traversal is to find two candidate modes, and the second traversal is to re-vote to verify whether the two candidate modes are public.
Implementation Code
C ++:
class Solution {public: vector
majorityElement(vector
& nums) { vector
res; int m = 0, n = 0, cm = 0, cn = 0; for (int 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 = 1; } else if (cn == 0) { n = nums[i]; 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; }};
Java:
public class Solution { public List
majorityElement(int[] nums) { List
res = new ArrayList
(); int m = 0, n = 0, cm = 0, cn = 0; for (int 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 (int a : nums){ if (a == m) { ++cm; } else if (a == n) { ++cn; } } if (cm > nums.length / 3) { res.add(m); } if (cn > nums.length / 3) { res.add(n); } return res; }}