Question1
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Solution
思路1: 排序之后中间的数即为答案,O(nlogn)
思路2: 扫一遍数组,用map存放出现次数,找出次数大于size/2的数,O(n)
int majorityElement(vector<int>& nums) {
map<int, int> cnt;
int n = nums.size()/2;
for (auto num : nums)
cnt[num]++;
for (auto num : cnt)
if (num.second > n)
return num.first;
}
思路3:看了discuss才发现一种神奇的算法->Boyer–Moore majority vote algorithm,也叫多数投票算法,时间O(n),空间O(1)。
Wiki:https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
Majority Vote A