题目:
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.
思路:
1、 分治算法
把数组平分为左右两部分,分别对这两部分求Majority element,得到lmajority和rmajority:
①如果两部分所求相等,则所得即为该数组的majority element;
②若不等则利用C++ STL的count函数,比较lmajority和rmajority哪个在数组中出现次数更多,即为majority element。
对于分成的两部分求Majority element同理也用到上述过程,一直分到每部分只有一个元素,该元素当然就是该部分的Majority element。
代码实现:
class Solution {
public:
int majorityElement(vector<int>& nums) {
return majority(nums , 0 , nums.size()-1);
}
private:
int majority(vector<int>& nums, int left , int right) {
if (left == right)
return nums[left];
int mid = left + ( right - left ) / 2;
int lmajority = majority ( nums , left , mid );
int rmajority = majority ( nums , mid + 1 , right );
if ( lmajority == rmajority )
return lmajority;
else
return (count (nums.begin() + left , nums.begin() + right + 1 , lmajority) > count (nums.begin() + left , nums.begin() + right + 1 , rmajority) ? lmajority : rmajority );
}
};
备注:
count(ivec.begin() , ivec.end() , searchValue);把标志范围内的元素与输入值比较,返回相等元素个数。
2、排序
将数组排序,找到数组的中位数即为Majority element。
STL中的nth_element()方法的使用 通过调用nth_element(start, start+n, end) 方法可以使第n大元素处于第n位置(从0开始,其位置是下标为 n的元素),并且比这个元素小的元素都排在这个元素之前,比这个元素大的元素都排在这个元素之后,但不能保证他们是有序的。
class Solution {
public:
int majorityElement(vector<int>& nums) {
nth_element(nums.begin(), nums.begin() + nums.size() / 2, nums.end());
return nums[nums.size() / 2];
}
};
3、Moore Voting Algorithm
class Solution {
public:
int majorityElement(vector<int>& nums) {
int majority ;
int count = 0 ;
for ( int i = 0 ; i < nums.size() ; i++ ) {
if ( count == 0 )
majority = nums [i];
if ( nums[i] == majority )
count ++ ;
else
count -- ;
}
return majority;
}
};