[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.
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; } };
相关文章推荐
- LeetCode169. Majority Element
- LeetCode 169. Majority Element
- leetcode题解-169. Majority Element && 189. Rotate Array
- 【LeetCode】169. Majority Element
- leetcode 每日一题 169. Majority Element
- 【LeetCode】169 - Majority Element
- 2017-09-12 LeetCode_169 Majority Element
- [leetcode] 169. Majority Element
- LeetCode 169 Majority Element
- leetCode 169. Majority Element 数组
- 169.[LeetCode]Majority Element
- 2018.03.07 leetcode 打卡 #169. Majority Element
- leetcode:169 Majority Element-每日编程第十一题
- LeetCode 169. Majority Element
- LeetCode 169:Majority Element
- Leetcode练习笔记——169. Majority Element
- Leetcode:169. Majority Element(找到数组中出现次数最多的元素)
- leetcode No169. Majority Element
- 【Leetcode】:169. Majority Element 问题 in Go语言
- Leetcode 169. Majority Element