LeetCode:169. Majority Element
2017-03-18 11:20
351 查看
Given an array of size n, find the majority element. The majority element is the element that appears more than
You may assume that the array is non-empty and the majority element always exist in the array.
一开始我的思路是对于每个数组中的元素都找到其出现的数目,如果出现超过n/2次那么return,这种方法结果出现超时。上网查找一下,发现有个很好的
方法:每找出两个不同的element,就成对删除即count--,最终剩下的一定就是所求的。
AC:
⌊ n/2 ⌋times.
You may assume that the array is non-empty and the majority element always exist in the array.
一开始我的思路是对于每个数组中的元素都找到其出现的数目,如果出现超过n/2次那么return,这种方法结果出现超时。上网查找一下,发现有个很好的
方法:每找出两个不同的element,就成对删除即count--,最终剩下的一定就是所求的。
AC:
class Solution { public: int majorityElement(vector<int>& nums) { int elem = 0; int count = 0; for(int i = 0; i < nums.size(); i++) { if(count == 0) { elem = nums[i]; count = 1; } else { if(elem == nums[i]) count++; else count--; } } return elem; } };
相关文章推荐
- leetcode--169. Majority Element
- LeetCode 169. Majority Element (数组的主要元素、摩尔投票算法)
- leetcode 169 Majority Element C++
- [LeetCode]--169. Majority Element
- LeetCode 169. Majority Element(Java)
- [LeetCode] 169. Majority Element
- 【一天一道LeetCode】#169. 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(169)Majority Element
- [leetcode]: 169. Majority Element
- LeetCode 169. Majority Element and LeetCode 229. Majority Element II解题报告
- LeetCode 169: Majority Element
- 2018.03.07 leetcode 打卡 #169. Majority Element
- 【LeetCode】169.Majority Element (Easy)
- Leetcode题解 169. Majority Element