leetcode Majority Element
2015-11-16 16:12
387 查看
Given an array of size n, find the majority element. The majority element is the element that appears more than
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
这道题我还是用map做的,对于某个关键字有这种计数类的性质的题目用map真的很好用,关键点还是记得map里面的元素是pair,我们需要(*i).first,最后是32ms,还不错吧
一次提交就accepted还是非常开心的。
后来还看了一种比较简单的思想,但是理解起来比较困难
In this problem, k equals to 2.
Thus we "remove" each pair of 2 different elements, and the remaining element that do not have its counterpart is the desired element.
就是成k对去“删除”不相同的元素:
例如5个元素的时候,5,3,4,3,3这种情况下,5,3会被删除,4,3会被删除,最后就剩下3;
5,3,3,4,3:5,3会被删除,3,4会被删除,留下3
5,3,3,3,4:5,3会被删除,candidate是第二个3,因为接下来的元素还是3,于是Ntimes变成了2,即使后面的4与其不相同,Ntimes没有被减至0,于是,被返回。
⌊ n/2 ⌋times.
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
这道题我还是用map做的,对于某个关键字有这种计数类的性质的题目用map真的很好用,关键点还是记得map里面的元素是pair,我们需要(*i).first,最后是32ms,还不错吧
一次提交就accepted还是非常开心的。
class Solution { public: int majorityElement(vector<int>& nums) { map<int,int> eleTimes; int temp=0,count=0,sta=0; sta=nums.size()/2; if(sta==0) return nums[0]; for(auto i=nums.begin();i!=nums.end();i++){ temp=(*i); ++eleTimes[temp]; } for(auto j=eleTimes.begin();j!=eleTimes.end();j++){ count=(*j).second; if(count>sta) return (*j).first; } } };
后来还看了一种比较简单的思想,但是理解起来比较困难
[C++ Solution] [O(n) computation/O(1) space] The problem can be extended to ⌊n/k⌋ situation
Find k different element, and "remove" them as a group, the remaining element must be the element that appears more than ⌊n/k⌋ times. (Detailed explanation is given in comment)In this problem, k equals to 2.
Thus we "remove" each pair of 2 different elements, and the remaining element that do not have its counterpart is the desired element.
就是成k对去“删除”不相同的元素:
例如5个元素的时候,5,3,4,3,3这种情况下,5,3会被删除,4,3会被删除,最后就剩下3;
5,3,3,4,3:5,3会被删除,3,4会被删除,留下3
5,3,3,3,4:5,3会被删除,candidate是第二个3,因为接下来的元素还是3,于是Ntimes变成了2,即使后面的4与其不相同,Ntimes没有被减至0,于是,被返回。
class Solution { public: int majorityElement(vector<int> &num) { int nTimes = 0; int candidate = 0; for(int i = 0; i < num.size(); i ++) { if(nTimes == 0) { candidate = num[i]; nTimes = 1; } else { if(candidate == num[i]) nTimes ++; else nTimes --; } } return candidate; } };
相关文章推荐
- 移动端网络优化
- eventbus
- IConfigurationSectionHandler 接口
- 表单重复提交问题解决
- 大数据量下高并发同步的讲解(不看,保证你后悔)
- spark graphx: creat an graph from csv
- Js获取当前日期时间及其它操作
- GreenDao使用入门
- mysql重复数据下,删除一条重复数据
- 内存检测工具valgrind
- 6.请求网络步骤
- 虚拟服务器使用E1000E类型的网卡,可能会 导致故障转移功能通信异常,不稳定
- JAVA加密C++解密简单方法
- iOS 9打印-canOpenURL: failed for URL
- 2015-11-16 【项目1 - 二叉树算法验证】
- Nginx服务器的安装与一些基本配置总结
- 【LeetCode-290】Word Pattern(C++)
- fir.im Weekly - iOS 保持界面流畅的技巧
- Ubuntu安装配置samba
- 12个用得着的jQuery代码片段