leetcode-169-Majority Element
2015-06-30 20:20
309 查看
Majority Element
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/2)。对数组排序,因为出现次数最多的数的次数大于n/2 ,故排序后最 中间的数,必为出现次数最多的数。
class Solution { public: int majorityElement(vector<int> &num) { int n = num.size(); sort(num.begin(),num.end()); return num[n/2]; } };因为要排序,所以 复杂度为O(nlogn)
也可以用复杂度为O(n)的算法
即,每找到两个不同的数,就成对删除,出现次数最多的元素最终会留下。因为次数做多的数出现次数大于n/2,所以最坏的情况下,也可以找出。
class Solution { public: int majorityElement(vector<int> &num) { int elem=0,count_=0; for(int i=0;i<num.size();i++){ if(!count_){ // count_==0 则将当前的数赋给elem elem=num[i]; count_=1; } else{ if(elem==num[i]) // 当前元素num[i]==elem 则count_++; count_++; else count_--; // 否则 成对删除 } } return elem; } };
相关文章推荐
- SQL 默认数据库被误删
- B\S备忘录21——使用反射将委托挂钩
- 黑马程序员——java的IO之字符流,字节流,转换流
- 日惹中文离线地图App上线
- node.js安装、使用
- 超漂亮Js+css图片幻灯切换
- Struts2学习--配置及原理简述
- 多目标优化的遗传算法及其改进(浮点数编码),对多个函数进行测试
- 随机获取一个集合(List, Set)中的元素,随机获取一个Map中的key或value
- iOS - 常用正则表达式判断邮箱、身份证..是否正确
- extern “C”
- 雅加达中文离线地图App上线
- gps软件预览
- Win7刚装完就用了40多个G
- 大型网站架构体系的演变(下)
- 看看我们熟知的17个行业如何被互联网所颠覆
- 默认端口:ftp,ssh,telnet,dhcp,mail,pop3,smtp,dns,http,sm等
- 检验身份证信息是否可靠。
- libsvm-3.12中的 README
- 忘记的C语言中的一些知识点