Majority Element
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.
采用分治算法 (Divide-and-Conquer algorithms)
class Solution {
public:
int majorityElement(vector<int>& nums) {
return Maj(nums, 0, nums.size() - 1);
}
private:
int Maj(vector<int>& nums, int left, int right) {
if (left == right) {
return nums[left];
}
int mid = left + ((right - left) >> 1);
int leftmaj = Maj(nums, left, mid);
int rightmaj = Maj(nums, mid + 1, right);
if (leftmaj == rightmaj) {
return leftmaj;
}
return count(nums.begin() + left, nums.begin() + right + 1, leftmaj) > count(nums.begin() + left, nums.begin() + right + 1, rightmaj) ? leftmaj : rightmaj;
}
};
class Solution {
public:
int majorityElement(vector<int>& nums) {
return Maj(nums, 0, nums.size() - 1);
}
private:
int Maj(vector<int>& nums, int left, int right) {
if (left == right) {
return nums[left];
}
int mid = left + ((right - left) >> 1);
int leftmaj = Maj(nums, left, mid);
int rightmaj = Maj(nums, mid + 1, right);
if (leftmaj == rightmaj) {
return leftmaj;
}
return count(nums.begin() + left, nums.begin() + right + 1, leftmaj) > count(nums.begin() + left, nums.begin() + right + 1, rightmaj) ? leftmaj : rightmaj;
}
};