当前位置:网站首页>剑指Offer03. 数组中重复的数字【简单】
剑指Offer03. 数组中重复的数字【简单】
2022-07-03 11:50:00 【伍六琪】
剑指 Offer 03. 数组中重复的数字
题目描述:
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
> 输入: [2, 3, 1, 0, 2, 5, 3]
> 输出:2 或 3
限制:
2 <= n <= 100000
JAVA代码
普通方法
两层遍历挨个寻找第一个重复的数字。
class Solution {
public int findRepeatNumber(int[] nums) {
for(int i = 0;i<nums.length-1;i++){
for(int j = i+1;j<nums.length;j++){
if(nums[i]==nums[j]){
return nums[i];
}
}
}
return -1;
}
}
Map方法
使用map存储nums数据,以nums的值作为map的key,当遇到相同的key值时返回该数值。
class Solution {
public int findRepeatNumber(int[] nums) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0;i<nums.length;i++){
if(map.containsKey(nums[i])){
return nums[i];
}
map.put(nums[i],i);
}
return -1;
}
}
官方方法
使用Set,仅存储一个值,比Map方法存储两个值更加简便
拓展:Set无序的不可重复的。add()方法返回false,则说明存在重复的值。
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
int result = -1;
for(int num:nums){
if(!set.add(num)){
result = num;
break;
}
}
return result;
}
}
“这里没有涉及到其他复杂的关于位置的操作,所以仅仅存储值就足够了。”
边栏推荐
- (构造笔记)从类、API、框架三个层面学习如何设计可复用软件实体的具体技术
- Is it safe to open an account for online stock speculation? Who can answer
- 实现验证码验证
- 145. Post order traversal of binary tree
- How to convert a numeric string to an integer
- Wechat applet pages always report errors when sending values to the background. It turned out to be this pit!
- 【附下载】密码获取工具LaZagne安装及使用
- temp
- Shutter widget: centerslice attribute
- Use of QT OpenGL camera
猜你喜欢
[learning notes] DP status and transfer
1-2 project technology selection and structure
Qt+vtk+occt reading iges/step model
Basic knowledge of OpenGL (sort it out according to your own understanding)
Itext7 uses iexternalsignature container for signature and signature verification
Develop plug-ins for idea
Summary of development issues
云计算未来 — 云原生
雲計算未來 — 雲原生
Shardingsphere sub database and sub table < 3 >
随机推荐
雲計算未來 — 雲原生
shardingSphere分库分表<3>
Summary of development issues
(数据库提权——Redis)Redis未授权访问漏洞总结
Download address and installation tutorial of vs2015
Itext7 uses iexternalsignature container for signature and signature verification
MySQL time zone solution
PHP get the file list and folder list under the folder
C language improvement article (wchar_t) character type
Flutter: self study system
Use bloc to build a page instance of shutter
elastic_ L01_ summary
023 ([template] minimum spanning tree) (minimum spanning tree)
(构造笔记)从类、API、框架三个层面学习如何设计可复用软件实体的具体技术
Flutter 退出登录二次确认怎么做才更优雅?
If you can't learn, you have to learn. Jetpack compose writes an im app (I)
init. RC service failed to start
AOSP ~ NTP (Network Time Protocol)
flinksql是可以直接客户端建表读mysql或是kafka数据,但是怎么让它自动流转计算起来呢?
Is BigDecimal safe to calculate the amount? Look at these five pits~~