当前位置:网站首页>【剑指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;
}
边栏推荐
- Calculate the number of combinations recursively
- 进程和计划任务管理
- Network Saboteur
- 作业8.9 构建TCP协议的服务器
- [target detection] small script: extract training set images and labels and update the index
- Send a post request at the front desk can't get the data
- LeetCode·297.二叉树的序列化与反序列化·DFS·BFS
- 图式图例规范尺寸
- 【量化交易行情不够快?】一文搞定通过Win10 wsl2 +Ubuntu+redis+pickle实现股票行情极速读写
- Error: Rule can only have one resource source (provided resource and test + include + exclude)
猜你喜欢
MySQL面试题整理
Redis 定长队列的探索和实践
bgp双平面实验 路由策略控制流量
2022年五大云虚拟化趋势
友邦人寿可观测体系设计与落地
ArcMAP has a problem of -15 and cannot be accessed [Provide your license server administrator with the following information:Err-15]
第三方软件测评有什么作用?权威软件检测机构推荐
M²BEV: Multi-Camera Joint 3D Detection and Segmentation with Unified Bird’s-Eye View Representation
AWS 安全基础知识
高数_证明_弧微分公式
随机推荐
简单的写一个防抖跟节流
LeetCode·297.二叉树的序列化与反序列化·DFS·BFS
Existing in the rain of PFAS chemical poses a threat to the safety of drinking water
MySQL interview questions
M²BEV: Multi-Camera Joint 3D Detection and Segmentation with Unified Bird’s-Eye View Representation
领域驱动实践总结(基本理论总结与分析V+架构分析与代码设计+具体应用设计分析)
作业
C# 当前上下文中不存在InitializeComponent()
【学习笔记】Redis的持久化
Vivado crashes or the message is not displayed
Nanodlp v2.2/v3.0 light curing circuit board, connection method of mechanical switch/photoelectric switch/proximity switch and system state level setting
bgp dual plane experiment routing strategy to control traffic
Pointer (preliminary solution of C language)
Error: Rule can only have one resource source (provided resource and test + include + exclude)
代码随想录笔记_动态规划_70爬楼梯
Makefile missing separator. Stop.怎么解决「建议收藏」
文件系统设计
A unit test report for CRM One Order Application log
商汤自研机械臂,首款产品是AI下棋机器人:还请郭晶晶作代言
接口自动化测试基础篇