169. Majority Element
2016-12-03 17:58
176 查看
题目
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++ 中的map
map中可以存储键值对。所以将数组的元素存到
map中 存储形式
<vector<i>,count>然后遍历
map找出最大值为止。
int majorityElement(vector<int>& nums) { map<int, int> im; for (auto e : nums) ++im[e]; int temp = im.begin()->second; int mE=im.begin()->first; for (auto e : im) if (e.second > temp){ temp = e.second; mE = e.first; } return mE; } }
方法二
出现最多的元素,根据题目知道一定超过了一半,我们可以遍历数组,当遇到相同数字时计数器就加一,当不同的时候就减一,如果计数器等于0了,那么这个数字肯定不是出现最多的。(因为出现最多的元素的次数超过了一半)int majorityElement(vector<int>& nums) { int mE = nums[0]; vector<int>::size_type index = 0; int count = 0; for (;index<nums.size();index++) { if (count == 0 || mE == nums[index]) { mE = nums[index]; count++; } else count--; } return mE; }
总结
方法一,因为要遍历两次,所以时间复杂度比方法二大相关文章推荐
- leetcode题解-169. Majority Element && 189. Rotate Array
- 169 Majority Element
- LeetCode(三)HashMap169. Majority Element&350. Intersection of Two Arrays II
- 169. Majority Element (divide and conquer)
- Divide and Conquer:169. Majority Element
- 169_Majority Element
- LeetCode(169)Majority Element
- Leetcode Algorithms - Divide and Conquer:169. Majority Element
- [Leetcode]#169 Majority Element
- 169. Majority Element
- 169. Majority Element
- 【LEETCODE】169-Majority Element
- 169.Majority Element
- 2018.03.07 leetcode 打卡 #169. Majority Element
- 【LeetCode】169. Majority Element (多数投票算法 & 算法迁移能力)
- 169. Majority Element
- 169. Majority Element
- 169. Majority Element My Submissions Question
- leetcode 169 Majority Element C++
- 169. Majority Element