当前位置:网站首页>【剑指offer】---数组中的重复数字
【剑指offer】---数组中的重复数字
2022-08-10 13:36:00 【半夏而凉】
第四次打卡!!!
活动地址:CSDN21天学习挑战赛
题目描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组[2,3,1,0,2,5,3],那么对应的输出是2或者3。存在不合法的输入的话输出-1。
数据范围:0≤n≤10000
进阶:时间复杂度O(n) ,空间复杂度O(n)
示例
输入:[2,3,1,0,2,5,3]
返回值:2
说明:2或3都是对的
代码
方法一:两层遍历
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param numbers int整型一维数组
* @return int整型
*/
public int duplicate (int[] numbers) {
// write code here
int n=numbers.length;
if(n<2) return -1;
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
if(numbers[i]==numbers[j])
return numbers[i];
}
}
return -1;
}
方法二:hashmap
public int duplicate (int[] numbers) {
// write code here
int n=numbers.length;
if(n<2) return -1;
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for (int i=0; i<n; i++){
if(!map.containsKey(numbers[i])){
map.put(numbers[i],i);
}
else return numbers[i];
}
return -1;
}
边栏推荐
- Cloud Migration Practice of Redis
- 22!Beijing Changping District notified catering service enterprises with food safety problems
- BEVDet4D: Exploit Temporal Cues in Multi-camera 3D Object Detection Paper Notes
- Code Casual Recording Notes_Dynamic Programming_70 Climbing Stairs
- Stream通过findFirst()查找满足条件的一条数据
- 2022年五大云虚拟化趋势
- 【学习笔记】Redis的持久化
- CodeForces-834C
- tampercfg内核模块导致机器频繁crash
- [Study Notes] Persistence of Redis
猜你喜欢
如何完成新媒体产品策划?
“Oracle 封禁了我的账户”
M²BEV: Multi-Camera Joint 3D Detection and Segmentation with Unified Bird’s-Eye View Representation
交换机的基础知识
什么?你还不会JVM调优?
ArcMAP has a problem of -15 and cannot be accessed [Provide your license server administrator with the following information:Err-15]
Redis 定长队列的探索和实践
Short read or OOM loading DB. Unrecoverable error, aborting now
高数_证明_曲率公式
BEVDet4D: Exploit Temporal Cues in Multi-camera 3D Object Detection 论文笔记
随机推荐
OTA自动化测试解决方案---整体方案介绍
一汽奥迪:持续34年聚焦品质与体验 立足市场需求推进产品迭代
A method that can make large data clustering 2000 times faster
广东10个项目入选工信部2021年物联网示范项目名单
借数据智能,亚马逊云科技助力企业打造品牌内生增长力
Fragment-hide和show
Nanodlp v2.2/v3.0 light curing circuit board, connection method of mechanical switch/photoelectric switch/proximity switch and system state level setting
【POI 2008, BLO】割点
【量化交易行情不够快?】一文搞定通过Win10 wsl2 +Ubuntu+redis+pickle实现股票行情极速读写
X5WebView使用
【ECCV 2022|Millions of Prizes】PSG Competition: Pursuing the "Most Comprehensive" Scene Understanding
shell:正则表达式及三剑客grep命令
Loudi Center for Disease Control and Prevention Laboratory Design Concept Description
leetcode 739. Daily Temperatures 每日温度(中等)
Pointer (preliminary solution of C language)
商汤自研机械臂,首款产品是AI下棋机器人:还请郭晶晶作代言
ArcMAP has a problem of -15 and cannot be accessed [Provide your license server administrator with the following information:Err-15]
C#WPF 图片在显示时没有问题,但在运行时图片显示不出来的解决
3DS MAX batch export file script MAXScript with interface
M²BEV: Multi-Camera Joint 3D Detection and Segmentation with Unified Bird’s-Eye View Representation