LeetCode[169. Majority Elemen] 难度[easy]
2016-09-15 19:38
375 查看
题目
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.
意思就是找出一个数组里面n个元素中出现次数大于n/2的元素
这道题可以有以下多种做法:
算法一:先排序,第n/2个元素就是要的结果,时间复杂度是O(nlogn)
class Solution { public: int majorityElement(vector<int>& nums) { int n = nums.size(); int *temp = new int ; for(int i=0;i<n;++i) temp[i] = nums[i]; sort(temp,temp+n); int result = temp[n/2]; delete [] temp; return result;; } };
算法二:使用map,把每个元素出现的次数记录下来,找出现次数大于n/2的元素,时间复杂度是O(nlogn)
class Solution { public: int majorityElement(vector<int>& nums) { int n = nums.size(); map<int,int> Map; for(int i=0; i<n; ++i) Map[nums[i]]++; for(int i=0; i<n; ++i) if(Map[nums[i]]>n/2) return nums[i]; return 0; } };
算法三:使用摩尔投票法,时间复杂度是O(n)
class Solution { public: int majorityElement(vector<int>& nums) { int count = 0 , n = nums.size() ,result; for(int i=0; i<n; ++i){ if(count==0) result = nums[i]; if(result==nums[i]) count++; else count--; } return result; } };
算法四:使用分治思想,把原来的数组分成两个小数组,若两个数字的Majority Element都知道了,则原来数组的Majority Element必定是这两个的其中一个,只要统计两个元素哪个出现次数多就可以找到,时间复杂度为O(nlogn)
(这里实现的时候有个小细节就是,向量nums要按引用传递,若按值传递会超时)
class Solution { public: int majorityElement(vector<int>& nums) { int n = nums.size(); return MajorityElement(nums,0,n-1); } private: int MajorityElement(vector<int>& nums,int low,int high){ if(low==high) return nums[low]; int mid = low + ((high-low) >> 1); int left = MajorityElement(nums,low,mid); int right = MajorityElement(nums,mid+1,high); if(left==right) return left; return count(nums.begin()+low,nums.begin()+high+1,left)>count(nums.begin()+low,nums.begin()+high+1,right)?left:right; } };
算法五:这个算法比较巧妙,在数列中随机取一个数,统计这个数字出现的次数,若大于n/2则结果就是这个,若不是则重新取,由于所求元素在数组中出现次数很多,所以选中的几率大,平均2次就可以选中,算法时间复杂度为O(n)
class Solution { public: int majorityElement(vector<int>& nums) { int n = nums.size(); srand(time(0)); while(true){ int idx = rand()%n; if(count(nums.begin(),nums.begin()+n,nums[idx])>n/2) return nums[idx]; } } };
相关文章推荐
- LeetCode [448. Find All Numbers Disappeared in an Array] 难度[easy]
- leetcode169: Majority Elemen
- LeetCode 169. Majority Element (Easy)
- Leetcode 刷题 Binary Search Easy难度经验总结
- LeetCode[136. Single Number] 难度[easy]
- LeetCode 169. Majority Element (Easy)
- leetcode 7 easy的难度但是还是再次的提醒了我 math的重要性
- 【LeetCode】169.Majority Element (Easy)
- 第二次做leetcode中的难度为easy的题-258
- LeetCode [292. Nim Game] 难度[easy]
- leetcode_169_Majority Element(C++)(easy)
- Leetcode解题笔记 169.Majority Element [Easy]
- Leetcode 169. Majority Element[easy]
- [Leetcode 169, Easy] Majority Element
- [leetcode]题解+经验总结 自己做法+评论区mostvotes汇总 (只包含部分easy难度)
- 169. Majority Element 难度:Easy 类别:分治
- leetcode 169 Majority Element(难易度:Easy)
- 【Leetcode-Easy-169】 Majority Element
- [leetcode 169. Majority Element]easy |week4
- Leetcode 169. Majority Element (Easy) (cpp)