229. Majority Element II
Problem statement:
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.
Solution one: hash table
Compared with 169. Majority Element. This problem asks us to find the elements appear more than n/3 times. But, the same idea.
The first solution also employs hash table which indexed by the value of each element and counts the appearance.
We loop the array and all elements in the hash table. Time complexity is O(n). Space complexity is O(n).
class Solution { public: vector<int> majorityElement(vector<int>& nums) { unordered_map<int, int> hash_table; // <value, #> for(auto num : nums){ hash_table[num]++; } vector<int> majority_elements; for(auto it : hash_table){ if(it.second > nums.size() / 3){ majority_elements.push_back(it.first); } } return majority_elements; } };
Solution two: counteract philosophy.
The general idea is as follows:
Find the most appeared top 2 elements.
Count their appearances.
Check if the appearances of these two elements are greater than n / 3, and return the correct answer.
Time complexity is O(n). Space complexity is O(n).
class Solution { public: vector<int> majorityElement(vector<int>& nums) { int first_cnt = 0, second_cnt = 0; int first = 0, second = 0; // find the top two appeared elements for (auto num : nums) { if (first == num) { first_cnt++; } else if (second == num) { second_cnt++; } else if (first_cnt == 0) { first = num; first_cnt = 1; } else if (second_cnt == 0){ second = num; second_cnt = 1; } else { first_cnt--; second_cnt--; } } // count the appearance of these two elements first_cnt = 0; second_cnt = 0; for (auto num : nums) { if (first == num) { first_cnt++; } else if (second == num) { second_cnt++; } } // check if the appearances of these two elements are grater than n / 3 vector<int> majority_elements; if (first_cnt > nums.size() / 3) { majority_elements.push_back(first); } if (second_cnt > nums.size() / 3) { majority_elements.push_back(second); } return majority_elements; } };