当前位置:网站首页>剑指 Offer | 03. 数组中重复的数字
剑指 Offer | 03. 数组中重复的数字
2022-08-04 22:04:00 【孤天野鹤】
剑指 Offer 03. 数组中重复的数字 - 力扣(LeetCode)https://leetcode.cn/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/今天开个坑,刷一波剑指offer(虽然零散刷过一点。。。
法一:利用HashSet可以快速查找的特点,将元素放入HashSet中并比较。
class Solution {
public int findRepeatNumber(int[] nums) {
HashSet<Integer> integers = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (integers.contains(nums[i])) {
return nums[i];
}
integers.add(nums[i]);
}
return -1;
}
}
法二:下标法, 不断交换元素,使元素与其对应下标 相同,直至发生冲突。
class Solution {
public int findRepeatNumber(int[] nums) {
// 遍历数组
for(int i = 0; i < nums.length; i++) {
// 之所以用while,是因为交换之后,该位置的元素任然没有在正确的位置
while(i != nums[i]){
if(nums[i] == nums[nums[i]]){
return nums[i];
}
// nums[i] 正确的位置在 nums[nums[i]]
int k = nums[nums[i]];
nums[nums[i]] = nums[i];
nums[i] = k;
}
}
return -1;
}
}
边栏推荐
- 遍历await方法的区别:以for和forEach为例
- Is the International Project Manager PMP certificate worth taking?
- 1、网页结构
- What does Xinchuang mean?Which industries are involved?Why develop Xinchuang?
- 热力学相关的两个定律
- rk3399-0.0 svc命令
- 用Tesseract开发一个你自己的文字识别应用
- Exploration and Practice of Database Governance
- Win11如何设置软件快捷方式?
- 力扣24-两两交换链表中的节点——链表
猜你喜欢
强网杯2022——WEB
Rt-thread [三] link.lds链接脚本详解
[Linear Algebra 02] 2 interpretations of AX=b and 5 perspectives of matrix multiplication
NFT宝典:你需要知道NFT的术语和定义
七夕,当爱神丘比特遇上牛郎和织女
【QT】回调函数的实现
【线性代数03】消元法展示以及AX=b的4种解情况
【TCP/IP 四 IP 网际协议】
【Social Marketing】WhatsApp Business API: Everything You Need to Know
基于声卡实现的音频存储示波器,可作为电磁学实验的测量仪表
随机推荐
# #ifndef/#define/#endif使用详解
三个多月、40余场面试浓缩为6000字
强网杯2022——WEB
移动web开发03
Webmine Webpage Mining Trojan Analysis and Disposal
ES6高级-Promise的用法
【uiautomation】微信好友列表获取(存储到txt中)
【Social Marketing】WhatsApp Business API: Everything You Need to Know
Unknown point cloud structure file conversion requirements
Autowired自动装配
ES 数据聚合、数据同步、集群
Axure9基本交互操作(一)
国内的PMP证书含金量到底如何
torch单机多卡和多机多卡训练
中大型商业银行堡垒机升级改造方案!必看!
rk3399 驱动屏参的几种方式
【组成原理 六 存储器类型】
Oracle使用expdp和impdp导出导入数据
可视化工作流引擎开发OA系统,让企业少花冤枉钱
Lecture 2 Software Life Cycle