Leetcode解题报告:169. Majority Element
来源:互联网 发布:手机端写php 编辑:程序博客网 时间:2024/05/16 13:49
题意:
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.
难度:Easy
解法一:
由于出现最多的那个元素出现了超过⌊ n/2 ⌋次 ,这意味着这个元素只可能有一个。 那么可以考虑将所有元素排序以后,处于中间位置的那个元素就是我们要找的元素了。 采取归并排序的方法,将一个序列不断拆分成两个子序列,然后再进行合并,最终获得一个排好序的序列。 归并排序的时间复杂度是O(nlogn),空间复杂度是O(n+logn)。归并排序的时间复杂度在排序算法中比较具有效率,但是需要牺牲空间。
class Solution {public:void Merge(vector<int>& s, vector<int>& t, int begin, int mid, int end){ int i =begin , j=mid+1, k=begin; while(i<=mid&j<=end) { if(s[i]>=s[j]) t[k++]=s[j++]; else t[k++]= s[i++]; } while(i <=mid) t[k++] = s[i++]; while(j <= end) t[k++] = s[j++]; for(i=begin; i<=end; i++) s[i] = t[i];} void MergeSort(vector<int>& s, vector<int>& t, int begin, int end){ int mid; if(begin < end) { mid = (begin+end) / 2; MergeSort(s,t,begin,mid); MergeSort(s,t,mid+1,end); Merge(s,t,begin,mid,end); }}int majorityElement(vector<int>& nums) {vector<int> a(nums.size()+1);MergeSort(nums,a,0,nums.size()-1);return nums[nums.size()/2];}<h2>};</h2>
注:参考资料《大话数据结构》 清华大学出版社
解法二:可以用借助map,以元素为关键字,出现次数为值,遍历一次所有元素,统计每个元素出现的次数。再遍历一次map中所有的数据,找出出现次数最多的那个关键字,这样就可以在O(n)的时间复杂度下完成这道题,而且空间复杂度也减小为了O(n),算法的性能比方法一有了明显的提高。
int majorityElement(vector<int>& nums) {map<int,int> mymap;for(int i = 0;i<nums.size();i++){mymap[nums[i]]++;}int max=-1;int ans;map<int,int> ::itrartor it;for(it = mymap.begin(); it!=mymap.end();it++){if(it->second>max){max=it->second;ans=it->first;}}return ans;}
0 0
- [leetcode] 169. Majority Element 解题报告
- Leetcode解题报告:169. Majority Element
- LeetCode解题报告 169. Majority Element [easy]
- LeetCode 169. Majority Element 解题报告
- 【LeetCode】169. Majority Element解题报告
- [Leetcode] 169. Majority Element 解题报告
- LeetCode-Majority Element -解题报告
- 【LeetCode】Majority Element 解题报告
- LeetCode 169. Majority Element and LeetCode 229. Majority Element II解题报告
- LeetCode-Majority Element II-解题报告
- [leetcode] 229. Majority Element II 解题报告
- 【LeetCode】229.Majority Element II解题报告
- [Leetcode] 229. Majority Element II 解题报告
- leetcode解题报告229——Majority Element II
- [LeetCode]169.Majority Element
- LeetCode 169.Majority Element
- 【LeetCode】169.Majority Element
- LeetCode 169. Majority Element
- Pixhawk参数调整
- x264预设类参数详解
- VC IAI HOOK demo
- 请教c语言swtich语句问题
- Unity LOD Study
- Leetcode解题报告:169. Majority Element
- Different Ways to Add Parentheses
- 【设计模式】抽象工厂模式
- ajax通过xml交互数据
- AJAX-jQuery中的AJAX封装函数
- Hadoop之Jobtracker启动过程
- 通过redis-cli的日志查看redis操作记录
- java-设计模式-创建模式-原型模式prototype
- Java:信号转换(注意考虑多种情况)