当前位置:网站首页>剑指 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;
}
}
边栏推荐
猜你喜欢

Bombard the headquarters. Don't let a UI framework destroy you

vscode插件自用

Problems encountered in using MySQL

Day_ ten

1-8file sharing in VMWare

2022-06-17 网工进阶(十)IS-IS-通用报头、邻接关系的建立、IIH报文、DIS与伪节点

Coredata data persistence

Knowing these interview skills will help you avoid detours in your test job search

How to talk about salary correctly in software testing interview

Read mysql45 the next day
随机推荐
解析数仓lazyagg查询重写优化
解析数仓lazyagg查询重写优化
Kalman filter meets deep learning: papers on Kalman filter and deep learning
APIJSON简单使用
Read mysql45 lecture - index
2022-06-17 advanced network engineering (x) is-is-general header, establishment of adjacency relationship, IIH message, DIS and pseudo node
_ 17 collection overview
ncnn源码学习全集
一个 TDD 示例
MySQL_ JDBC
XXIX - orbslam2 real-time 3D reconstruction using realsensed435
Xinlou: Huawei's seven-year building journey of sports health
WPF开发随笔收录-心电图曲线绘制
【精通高并发】深入理解汇编语言基础
1-8file sharing in VMWare
使用hbuilder X创建uniapp项目
2022-06-17 网工进阶(十)IS-IS-通用报头、邻接关系的建立、IIH报文、DIS与伪节点
Kalman Filter 遇到 Deep Learning : 卡尔曼滤波和深度学习有关的论文
Deadlock, thread communication, singleton mode
Common APIs and exception mechanisms