题目:
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.
思想很简单,就是超过一半的那个数输出出来。一想肯定是要计数了。如果用两个for那就复杂度是O(n^2)了,那就用一个Map,给每个数都计数,然后当大于一半的时候就输出。这时的复杂度是O(n)。
贴代码:
class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int, int>hash;
int size = nums.size();
for(int i = 0; i < size; ++i){
hash[nums[i]]++;
if(hash[nums[i]] > size/2){
return nums[i];
}
}
}
};
咦,等等,这个题是分治算法中的一道,为啥没用分治算法。
思考,如何用分治算法呢。。想了想,难道是用分治排序,然后因为有大于一半的,所以中位数一定就是大于一半的那个值?用到了数学知识。但这个分治有点强行加上去啊。。
这周有点忙,先做这一道简单的,有空再做其他的。