题目描述:
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.
找到这个数组中出现次数超过n/2次的元素,假设这个元素一定是存在的。
一个简单的方法就是排序后找中间的元素,代码如下:
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums[nums.size() / 2];
}
};
还有一种方法就是分而治之,每次将这个数组分为两半分别去找两边的主元素,若两边的主元素不同则利用count方法比较出现次数,时间复杂度略优
class Solution {
public:
int majorityElement(vector<int>& nums) {
return divideMajor(nums, 0, nums.size() - 1);
}
int divideMajor(vector<int>& nums, int begin, int end) {
if (begin == end) {
return nums[begin];
}
int leftM = divideMajor(nums, begin, (begin + end) / 2);
int rightM = divideMajor(nums, (begin + end) / 2 + 1, end);
if (leftM == rightM) {
return leftM;
}
if (count(nums.begin() + begin, nums.begin() + end+1, leftM) < count(nums.begin() + begin, nums.begin() + end+1, rightM)) {
return rightM;
}
else {
return leftM;
}
}
};