0229.cpp (747B)
1 class Solution { 2 public: 3 vector<int> majorityElement(vector<int> &nums) { 4 int a = -1, b = -1, ca = 0, cb = 0; 5 for (const int n : nums) { 6 if (n == a) 7 ca++; 8 else if (b == n) 9 cb++; 10 else if (!ca) 11 a = n, ca = 1; 12 else if (!cb) 13 b = n, cb = 1; 14 else 15 ca--, cb--; 16 } 17 ca = cb = 0; 18 for (const int n : nums) { 19 if (n == a) 20 ca++; 21 else if (n == b) 22 cb++; 23 } 24 25 vector<int> res; 26 if (ca > nums.size() / 3) res.push_back(a); 27 if (cb > nums.size() / 3) res.push_back(b); 28 return res; 29 } 30 };