当前位置:网站首页>【刷题篇】多数元素(超级水王问题)
【刷题篇】多数元素(超级水王问题)
2022-07-03 03:52:00 【m0_60631323】
一、题目
OJ链接
给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
要求:时间复杂度O(N) 空间复杂度O(1)
二、题解
2.1思路
核心思路:
详细流程:
2.2源码:
public int majorityElement(int[] arr) {
int cand=0;
int HP=0;
for (int i = 0; i < arr.length; i++) {
if(HP==0){
cand=arr[i];
HP=1;
}else if(cand==arr[i]){
HP++;
}else {
HP--;
}
}
return cand;
}
边栏推荐
- 小程序获取用户头像和昵称
- Docker install and start MySQL service
- 在 .NET 6 项目中使用 Startup.cs
- Use three JS make a simple 3D scene
- js中#号的作用
- MongoDB基本操作【增、删、改、查】
- Intercept string fixed length to array
- Error in compiled file: error: unmapped character encoding GBK
- What is pytorch? Is pytorch a software?
- Ffmpeg download and installation tutorial and introduction
猜你喜欢
Ffmpeg recording screen and screenshot
FileZilla client download and installation
TCP/IP模型中的重磅嘉宾TCP--尚文网络奎哥
Ffmpeg one / more pictures synthetic video
Web session management security issues
在写web项目的时候,文件上传用到了smartupload,用了new string()进行转码,但是在数据库中,还是会出现类似扑克的乱码
Wechat applet + Alibaba IOT platform + Hezhou air724ug built with server version system analysis
ffmpeg之 一张/多张图片合成视频
2022deepbrainchain biweekly report no. 104 (01.16-02.15)
2022 tea master (primary) examination questions and tea master (primary) examination question bank
随机推荐
Debug: CD cannot be used in kaggle
Makefile demo
The latest analysis of the main principals of hazardous chemical business units in 2022 and the simulated examination questions of the main principals of hazardous chemical business units
QQ小程序开发之 一些前期准备:预约开发账号、下载安装开发者工具、创建qq小程序
Table structure of Navicat export database
Pytorch multi card distributed training distributeddataparallel usage
105. Detailed introduction of linkage effect realization of SAP ui5 master detail layout mode
Web session management security issues
C语言HashTable/HashSet库汇总
动态规划:最长回文子串和子序列
Is pytorch open source?
简易版 微信小程序开发之for指令、上传图片及展示效果优化
Error c2694 "void logger:: log (nvinfer1:: ilogger:: severity, const char *)": rewrite the restrictive exception specification of virtual functions than base class virtual member functions
小程序获取用户头像和昵称
Advanced redis applications [password protection, data persistence, master-slave synchronization, sentinel mode, transactions] [not completed yet (semi-finished products)]
Makefile demo
Filter
[combinatorics] basic counting principle (addition principle | multiplication principle)
Web会话管理安全问题
[mathematical logic] propositional logic (judgment of the correctness of propositional logic reasoning | formal structure is eternal truth - equivalent calculus | deduction from premise - logical reas