当前位置:网站首页>剑指Offer刷题记录——Offer 03. 数组中重复的数字
剑指Offer刷题记录——Offer 03. 数组中重复的数字
2022-07-17 05:22:00 【什么时候点菜】
找出数组中重复的数字。 在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。 示例 1: 输入: [2, 3, 1, 0, 2, 5, 3] 输出:2 或 3 限制: 2 <= n <= 100000
方式1:自己做的本币方法(遍历)
public int findRepeatNumber(int[] nums) {
for (int i = 0;i < nums.length;i++){
for (int j = i + 1;j < nums.length;j++){
if (nums[i] == nums[j])
return nums[i];
}
}
return -1;
}时间复杂度O(n*n),空间复杂度O(1),记得算法老师说过,做任何替不要先想到暴力遍历的方法,基本上都会存在比它更好的方法的。
方式2:使用HashSet存储数据,因为HashSet不允许重复数据存在,则如果添加过程中出现错误就说明重复了:
public int findRepeatNumber1(int[] nums){
HashSet<Integer> set = new HashSet<>();
int repeat = -1;
for(int num : nums){
if(!set.add(num)){
repeat = num;
break;
}
}
return repeat;
}这里忘了增强for循环啥格式了,搜到后记住:
for(元素数据类型 变量:数组或者Collection集合){使用变量即可}
时间复杂度 O(N)O(N) : 遍历数组使用 O(N)O(N) ,HashSet 添加与查找元素皆为 O(1)O(1) 。
空间复杂度 O(N)O(N) : HashSet 占用 O(N)O(N) 大小的额外空间。
方式3:来着力扣大佬的:原地交换:
题目说明尚未被充分使用,即 在一个长度为 n 的数组 nums 里的所有数字都在 0 ~ n-1 的范围内 。 此说明含义:数组元素的 索引 和 值 是 一对多 的关系。
因此,可遍历数组并通过交换操作,使元素的 索引 与 值 一一对应(即 nums[i] = i)。因而,就能通过索引映射对应的值,起到与字典等价的作用。
遍历中,第一次遇到数字 x 时,将其交换至索引 x 处;而当第二次遇到数字 x 时,一定有 nums[x] =x ,此时即可得到一组重复数字。
算法流程:
遍历数组 nums ,设索引初始值为 i = 0i=0 :
若 nums[i] = i: 说明此数字已在对应索引位置,无需交换,因此跳过;
若 nums[nums[i]] = nums[i]: 代表索引 nums[i]处和索引 i 处的元素值都为 nums[i] ,即找到一组重复值,返回此值 nums[i];
否则: 交换索引为 i 和 nums[i]的元素值,将此数字交换至对应索引位置。
若遍历完毕尚未返回,则返回 -1。
复杂度分析:
时间复杂度 O(N): 遍历数组使用 O(N),每轮遍历的判断和交换操作使用 O(1)。
空间复杂度 O(1): 使用常数复杂度的额外空间。
public int findRepeatNumber2(int[] nums){
int i = 0;
while (i < nums.length){
if (nums[i] == i){
i++;
continue;
}
if (nums[nums[i]] == nums[i])
return nums[i];
int temp = nums[i];
nums[i] = nums[temp];
nums[temp] = temp;
}
return -1;
}共勉!
边栏推荐
猜你喜欢

Tianyi cloud Hangzhou virtual machine (VPS) performance evaluation

5G时代服务器在这里面起着什么作用?

Text three swordsman's awk command -- interception

小迪网络安全-笔记 加密编码算法(6)

【自动化测试】——robotframework实战(二)新建测试用例

我的世界1.12.2 神奇宝贝(精灵宝可梦) 开服教程

Comparison between CS brand SD NAND and SPI NAND

What is data center?
Xiaodi network security notes - Information Collection - architecture, construction, WAF (8)

Slag learning road (2) pure white direction: win Server 2003 server building
随机推荐
What is tsd/qsd? What is CS Genesis SD NAND?
银河麒麟桌面操作系统V10SP1(X86)安装SQL Developer
Gnome 安装扩展插件(40.1版本,opensuse tumbleweed)。
BigDecimal中divide方法
[jmeter] TCP Sampler
tail -f暂停方法
opensuse 安装网易云音乐(tumbleweed)(leap)
IP103.53.125.xxx IP地址段 详解
小迪网络安全-笔记(2)
汉诺塔2(函数)
Gentoo安装教程(Systemd+Gnome)
Xiaodi network security - note encryption coding algorithm (6)
[automated testing] - robotframework practice (I) building environment
手动字符串比较(指针题)
Maomao goes to work (recursive)
How to determine the electronic gear ratio of servo motor?
University
小迪网络安全-笔记(4)
Personal information management system
Tcp/ip four layer model and related configurations of F5