您的位置:首页 > 其它

[LeetCode] 169. Majority Element

2017-07-05 10:54 323 查看
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.

// 直接hash统计每个元素的出现次数。可知,必然仅有一个主要元素。
// 因此,当某元素的出现次数超过半数的时候,可以直接返回。
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> count;
const int n = nums.size();

for (auto num : nums) {
if (count[num]++ > n / 2)
return num;
}
}
};






// 基本思路,由于majority element是占半数以上的元素,那么在把数组排序之后,其必然会占据数组的中间位置。
// 作为优化,我们只需要局部排序即可。有点类似快排中的pivot。
class Solution {
public:
int majorityElement(vector<int>& nums) {
const int n = nums.size();
nth_element(nums.begin(), nums.begin() + n / 2, nums.end());
return nums[n / 2];
}
};






class Solution {
public:
int majorityElement(vector<int>& nums) {
return majorityElement(nums, 0, nums.size());
}
private
4000
:
int majorityElement(vector<int>& nums, int lo, int hi) {
if (lo == hi) return nums[lo];

int mid = lo + (hi - lo) / 2;

int lme = majorityElement(nums, lo, mid);
int rme = majorityElement(nums, mid + 1, hi);
if (lme == rme) return lme;

int lmecnt = count(nums.begin() + lo, nums.begin() + hi + 1, lme);
int rmecnt = count(nums.begin() + lo, nums.begin() + hi + 1, rme);
return lmecnt > rmecnt ? lme : rme;
}
};




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: