当前位置:网站首页>剑指 Offer 39. 数组中出现次数超过一半的数字
剑指 Offer 39. 数组中出现次数超过一半的数字
2022-06-25 16:34:00 【grt要一直一直努力呀】
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}
}
利用此种方法是可以通过的,但显然Arrays.sort不是本题考察的重点。
摩尔投票法
class Solution {
public int majorityElement(int[] nums) {
int x = 0, votes = 0;
for(int num : nums){
if(votes == 0) x = num;
votes += num == x ? 1 : -1;
}
return x;
}
}
边栏推荐
- Xinlou: un voyage de sept ans de Huawei Sports Health
- 这些老系统代码,是猪写的么?
- Paper notes: generalized random forests
- A complete collection of APP testing tools. It's enough to collect this one
- The problem of missing precision of kettle table input components
- 微信公众号服务器配置
- 論文筆記:LBCF: A Large-Scale Budget-Constrained Causal Forest Algorithm
- JVM内存结构
- How did I get a salary increase of 13k+ after one year of employment?
- Day21 multithreading
猜你喜欢
心楼:华为运动健康的七年筑造之旅
Precautions for function default parameters (formal parameter angle)
Android修行手册之Kotlin - 自定义View的几种写法
Perfect shuffle problem
The third day of mysql45
使用hbuilder X创建uniapp项目
Do you know all the configurations of pychrm?
Day_ thirteen
Kalman filter meets deep learning: papers on Kalman filter and deep learning
3年,我是如何涨薪到20k?
随机推荐
代码注释的艺术,优秀代码真的不需要注释吗?
居家办公让我绩效拿了C | 社区征文
SDN系统方法 | 10. SDN的未来
Day_ fourteen
效应与定律
The problem of missing precision of kettle table input components
This latest research has revealed two secrets of cloudy development
协议和分层次
Xinlou: un voyage de sept ans de Huawei Sports Health
万卷书 - 大力娃的书单
The third day of mysql45
Unity技术手册 - 生命周期旋转RotationOverLifetime-速度旋转RotationBySpeed-外力ExternalForces
Unity技术手册 - 干扰/噪音/杂波(Noise)子模块
Kalman filter meets deep learning: papers on Kalman filter and deep learning
Multiple decorators decorate a function
Data type variable operator
Ad domain login authentication
一个 TDD 示例
WPF开发随笔收录-心电图曲线绘制
【精通高并发】深入理解汇编语言基础