169. Majority Element
2017-09-23 16:27
183 查看
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.
数组中出现次数超过一半的数字
C++(19ms):
1 class Solution { 2 public: 3 int majorityElement(vector<int>& nums) { 4 int len = nums.size() ; 5 int res = nums[0] ; 6 int times = 1 ; 7 for (int i = 1 ; i < len ; i++){ 8 if (times == 0){ 9 res = nums[i] ; 10 times = 1 ; 11 }else if (res == nums[i]){ 12 times++ ; 13 }else{ 14 times-- ; 15 } 16 } 17 times = 0 ; 18 for(int i = 0 ; i < len ; i++){ 19 if (res == nums[i]) 20 times++ ; 21 } 22 if (times*2 <= len) 23 res = 0 ; 24 return res ; 25 } 26 };
相关文章推荐
- leetcode_c++:Majority Element(169)
- 169. Majority Element
- 小白笔记-------------------------------leetcode(169. Majority Element)
- 169. Majority Element
- 169. Majority Element
- Majority Element(169) && Majority Element II(229)
- LeetCode169 Majority Element
- LeetCode 169 --- Majority Element
- 169. Majority Element
- leetcode--169. Majority Element
- 169. Majority Element
- LeetCode 169.Majority Element--Divide and Conquer(分治法)
- LeetCode(169) Majority Element (Java)
- LeetCode 169 Majority Element
- 2018.03.07 leetcode 打卡 #169. Majority Element
- leetcode 169 Majority Element 冰山查询
- LeetCode 169. Majority Element
- 169 Majority Element
- 169. Majority Element
- 【leetcode】Array—— Majority Element(169)