原题目:
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 ⌋的数,记为m。可以有多中实现方法,这里只列举两种典型的做法。
(1)分治算法:因为m出现次数大于其他所有元素出现次数之后,所以可以通过不断删除两个不同的元素,最后留下的一个或者两个数便是m。具体实现如下:
class Solution {
public:
int majorityElement(vector<int>& nums) {
if(nums.size()<=2) return nums[0];
int i, n = nums.size();
for(i=1; i<n; i++)
if(nums[i] != nums[0])
{
int t;
if(i == n-1)
{
t = nums[0];
nums[0] = nums[n-2];
nums[n-2] = t;
}
else
{
t = nums[0];
nums[0] = nums[n-1];
nums[n-1] = t;
t = nums[i];
nums[i] = nums[n-2];
nums[n-2] = t;
}
nums.erase(nums.end() - 1);
nums.erase(nums.end() - 1);
break;
}
if(i == n) return nums[0];
return majorityElement(nums);
}
};
(2)排序找中位数:先将数组排序,由于m出现次数大于 ⌊ n/2 ⌋,中位数便是要找的数,这种方法实现简单,时间复杂度为O(nlogn)。
#include <algorithm>
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums[nums.size()/2];
}
};