题目:
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.
这道题目本来可以用哈希表来解决,不过题目要求用分治算法的思想,所以没有使用。因为想不出将该问题拆分为小问题的方法,所以参考了网上的思路,采用一种似乎不是很常规的分治算法(感觉跟标准的分治还是有点区别)。这种方法是基于如果一个数在这个数组中是出现次数最多的,那么在删去一对不同的数后剩下的子数组中,该数也是出现次数最多的。这种算法名为Moore Voting Algorithm。
提交代码:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int index = 0, count = 1;
for(int i = 1; i < nums.size(); i++) {
if(nums[i] == nums[index])
count++;
else
count--;
if(count == 0) {
count = 1;
index = i;
}
}
return nums[index];
}
};
这道题目还有延伸,也就是返回该数组中所有的出现次数超过k次的数(k小于n/2)。
可以参考以下网址:
http://www.cnblogs.com/JimmyTY/p/5020871.html