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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
找出数组中个数超过了n/2个的元素。
注意:测试用例中数组不为空并且一定会出现Majority元素
1 Hash表计数法
class Solution { public: int majorityElement(vector<int>& nums) { map<int, int> counts; for (int i = 0; i<nums.size(); i++) { if (counts.find(nums[i]) == counts.end()) { counts[nums[i]] = 0; } counts[nums[i]]++; if (counts[nums[i]]>nums.size() / 2) { return nums[i]; } } return 0; } }
2 Moore voting algorithm
class Solution { public: int majorityElement(vector<int>& nums) { int count = 0; int elem = 0; for (int i = 0; i<nums.size(); i++) { if (count == 0) { elem = nums[i]; count++; } else { if (elem == nums[i]) { count++; } else { count--; } } } return elem; } }转载请注明出处
:
http://www.zgljl2012.com/leetcode-169-majority-element/