LeetCode : Majority Element
2016-09-29 20:50
309 查看
思路1
数组经过快速排序,返回数组中间的值。超时。(直接使用sort函数会通过,而且比哈希表快)void myQuickSort(vector<int>& nums, int begin, int end) { if(begin < end) { int l = begin, r = end; int flag = nums[l]; while(l < r) { while(l < r && nums[r] >= flag) r--; nums[l] = nums[r]; while(l < r && nums[l] < flag) l++; nums[r] = nums[l]; } nums[l] = flag; myQuickSort(nums, begin, l - 1); myQuickSort(nums, l + 1, end); } } int majorityElement(vector<int>& nums) { int end = nums.size() - 1; myQuickSort(nums, 0, end); return nums[nums.size() / 2]; }
思路2
使用哈希表记录。int Solution::majorityElement(vector<int>& nums) { map<int, int> rec; for(int i = 0; i < nums.size(); i++) { if(rec.find(nums[i]) != rec.end()) rec[nums[i]] ++; else rec[nums[i]] = 1; if(rec[nums[i]] > nums.size() / 2) return nums[i]; } return -1; }
相关文章推荐
- leetcode 169---Majority Element
- 2018.03.07 leetcode 打卡 #169. Majority Element
- Leetcode 之 Majority Element I-- HashMap法以及 摩尔投票法
- LeetCode--Majority Element II & 多数投票算法
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- 小白笔记-------------------------------leetcode(169. Majority Element)
- leetcode 日经贴,Cpp code -Majority Element
- Leetcode练习笔记——169. Majority Element
- LeetCode Problem 169: Majority Element查找多数元素
- Leetcode 169. Majority Element
- leetcode Majority Element
- 和大神们学习每天一题(leetcode)-Majority Element
- leetcode_Majority Element (找出现次数大于一半的元素)-easy
- [Leetcode,python] Majority Element 众数
- Leetcode ☞ 169. Majority Element
- [LeetCode] Majority Element
- [Leetcode从零开刷]169.Majority Element
- Leetcode 169. Majority Element