# LeetCode第169题解析

输入: [3,2,3]

输入: [2,2,1,1,1,2,2]

class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums[ nums.size() / 2];
}
};

class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> unmap;
for(auto& num : nums) {
if(++unmap[num] > nums.size() / 2)
return num;
}
return 0;
}
};

class Solution {
public:
int majorityElement(vector<int>& nums) {
int n = 0;
int candidate;
for(auto& num : nums) {
if(n == 0) candidate = num;
if(candidate == num) n++;
else n--;
}
return candidate;
}
};

class Solution {
int count_in_range(vector<int>& nums, int target, int lo, int hi) {
int count = 0;
for (int i = lo; i <= hi; ++i)
if (nums[i] == target)
++count;
return count;
}
int majority_element_rec(vector<int>& nums, int lo, int hi) {
if (lo == hi)
return nums[lo];
int mid = (lo + hi) / 2;
int left_majority = majority_element_rec(nums, lo, mid);
int right_majority = majority_element_rec(nums, mid + 1, hi);
if (count_in_range(nums, left_majority, lo, hi) > (hi - lo + 1) / 2)
return left_majority;
if (count_in_range(nums, right_majority, lo, hi) > (hi - lo + 1) / 2)
return right_majority;
return -1;
}
public:
int majorityElement(vector<int>& nums) {
return majority_element_rec(nums, 0, nums.size() - 1);
}
};

10-19 672
02-20 32
11-29 109
12-17 143
12-23 1003