169. Majority Element
2016-07-07 07:46
239 查看
思路:
设置一个counter,并且用res记录第一个数字,从第二个开始,如果这个数和前一个数是一样的,那么counter++,如果不一样,就把counter--,如果counter变成0了,就把res放到当前数字上。一遍走完,返回res就好了。
因为majority的数字超过一半,它总能中和调别的数。
设置一个counter,并且用res记录第一个数字,从第二个开始,如果这个数和前一个数是一样的,那么counter++,如果不一样,就把counter--,如果counter变成0了,就把res放到当前数字上。一遍走完,返回res就好了。
因为majority的数字超过一半,它总能中和调别的数。
public int majorityElement(int[] nums) { if(nums.length == 0) { return 0; } int counter = 1; int res = nums[0]; for(int i = 1; i < nums.length; i++) { if(nums[i] == res) { counter++; } else { counter--; if(counter == 0) { counter = 1; res = nums[i]; } } } return res; }
相关文章推荐
- 一起学微软Power BI系列-官方文档-入门指南(4)Power BI的可视化
- Winbuntu,Win 10 的 Ubuntu 运行环境
- 牛顿法求平方根
- 5h2w
- PAT 1020. 月饼 (25)
- Problem4-1018
- android 监控应用进程
- EventBus 3.0源码解析
- ******Eclipse 快捷键******
- 软件设计规划
- 全局最小割 学习总结
- codeforces 375D Tree and Queries
- Go入门:怎样编写Go代码
- Linux shell中运行命令后加上字符“&”的作用
- 教案、讲稿、讲义的区别
- Spring
- 分治最小割 学习总结
- VisualSVN服务器与TortoiseSVN客户端的安装
- Spark基础:使用维基百科数据集来用Spark进行原型实验
- 在Spark和Hadoop上做大规模数据科学