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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
分析
分而治之。若nums只含一个数,则该数就是主元。若多于一个数,将nums分为两部分,若两部分都没有主元,则nums没有主元,若左右部分的主元相等,那么该数就是主元。若左右两边的主元不相等,扫描nums,统计该数的次数,若大于size/2,该数就是主元。
代码
class Solution {
public:
int majorityElement(vector<int>& nums) {
int size=nums.size();
if (size==1)
return nums[0];
vector<int> left=vector<int>(nums.begin(),nums.begin()+size/2);
vector<int> right=vector<int>(nums.begin()+size/2,nums.end());
int left_major=majorityElement(left);
int right_major=majorityElement(right);
int tem;
if (left_major==-1&&right_major==-1) {
return -1;
} else if (left_major==right_major) {
return left_major;
} else {
if (left_major!=-1) {
tem=left_major;
int count = 0;
for (int i = 0; i < size; ++i) {
if (nums[i]==tem)
count++;
}
if (count>size/2)
return tem;
}
if (right_major!=-1) {
tem=right_major;
int count = 0;
for (int i = 0; i < size; ++i) {
if (nums[i]==tem)
count++;
}
if (count>size/2)
return tem;
}
return -1;
}
}
};