[LintCode]46.主元素
来源:互联网 发布:主机屋绑定域名 编辑:程序博客网 时间:2024/05/16 08:17
给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
样例
给出数组[1,1,1,1,2,2,2],返回 1
思路:把这些数看做两种类型,一种主元素,一种非主元素;如果每次我们都从这两种类型中各拿走一个数,直到其中一种类型的数拿光,则最后,剩下的一种类型必定会是主元素类型。记录两个量,当前元素result,计数count。初始化count为0;然后遍历序列,若count为0,则将result设为当前元素并将count置为1,否则,若当前元素和result相同,那么count++,若当前元素和count不同,那么cnt--;遍历结束以后,result即为主元素。
class Solution {public: /** * @param nums: A list of integers * @return: The majority number */ int majorityNumber(vector<int> nums) { int size=nums.size(); int result=0,count=0; if(size > 0) { for(int i=0; i<size; i++) { if(count == 0) { result = nums[i]; count = 1; }else { if(result == nums[i]) { count++; }else{ count--; } } } return result; } }};
阅读全文
0 0
- [LintCode]46.主元素
- LintCode 46.主元素
- Lintcode 主元素
- LintCode-主元素
- 主元素(LintCode)
- lintcode 主元素
- 主元素-----lintcode
- LintCode:主元素 III
- LintCode 主元素
- lintcode ----主元素
- LintCode(easy)主元素
- lintcode,主元素
- LintCode 主元素
- LintCode :主元素
- Lintcode 主元素 III
- LintCode 46 主元素
- [Lintcode]主元素
- Lintcode 主元素
- 关于自家小麦被邻家大牛吃掉的问题的思考
- 关于GAN的问题
- 序列式容器 vector
- 4.IPv4和IPv6地址长度
- itween 简单使用
- [LintCode]46.主元素
- Cross-view Action Recognition 跨视角动作识别方法
- 数据段、代码段、堆栈段、BSS段的区别
- HDU 5692(DFS序,线段树)
- 在VC2015里发现gets函数不存在的错误
- 仿美团外卖,饿了吗 两个ListView联动,左边点击切换右边,右边滑动切换左边
- 遗传算法及其应用part2
- 理解js中的constructor 和prototype
- Docker network命令