当前位置:网站首页>【力扣】645.错误的集合
【力扣】645.错误的集合
2022-07-25 13:38:00 【aigo-2021】
集合 s 包含从 1 到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个数字复制了成了集合里面的另外一个数字的值,导致集合 丢失了一个数字 并且 有一个数字重复 。
给定一个数组 nums 代表了集合 S 发生错误后的结果。
请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。
示例 1:
输入:nums = [1,2,2,4]
输出:[2,3]
示例 2:
输入:nums = [1,1]
输出:[1,2]
提示:
2 <= nums.length <= 104
1 <= nums[i] <= 104
代码:
class Solution {
public int[] findErrorNums(int[] nums) {//nums:[1,2,2,4,5]
int[] arr=new int[2];//存储返回结果
int[] temp=new int[nums.length+1];//初始temp:[0,0,0,0,0,0]
for(int i=0;i<nums.length;i++){
//将nums[i]的值,作为temp的下标,放到下表对应的位置上,每放一次temp[nums[i]]的数值就加1
temp[nums[i]]++;
}//循环结束后 temp:[0,1,2,0,1,1]
//则temp数组中元素值为2对应的下标是重复数字,元素值为0对应的下标是丢失数字(第一个零除外)
for(int i=1;i<temp.length;i++){
if(temp[i]==2) arr[0]=i;
if(temp[i]==0) arr[1]=i;
}
return arr;
}
public static void main(String[] args) {
Solution s=new Solution();
System.out.println(Arrays.toString(s.findErrorNums(new int[]{1,2,2,4,5})));
}
}题目核心是利用数组的下标来表示元素,以达到不使用set集合的目的。
易错测试用例:
输入:nums=[2,2]
输出:[2,1] 而不是[2,3]
原因:未读清题目, 题中说的是 集合 s 包含从 1 到 n 的整数,也就是集合s一定是从1开始的。
边栏推荐
- Blindly expanding the scale of the meta universe has deviated from the development logic of the meta universe
- 0717RHCSA
- Friends let me see this code
- 并发编程之并发工具集
- ES6 array de duplication new set()
- 0716RHCSA
- Programmer growth chapter 27: how to evaluate requirements priorities?
- 互斥锁、自旋锁、读写锁……理清它们的区别和应用
- @wrap 装饰器
- In order to improve efficiency, there are various problems when using parallelstream
猜你喜欢

Based on Baiwen imx6ull_ Pro development board transplants LCD multi touch driver (gt911)

【CTR】《Towards Universal Sequence Representation Learning for Recommender Systems》 (KDD‘22)

Design and principle of thread pool

刷题-洛谷-P1161 开灯

刷题-洛谷-P1047 校门外的树

GCD details

安装mujoco报错:distutils.errors.DistutilsExecError: command ‘gcc‘ failed with exit status 1

2022年下半年软考信息安全工程师如何备考?

QGIS loading online map: Gaode, Tiandi map, etc

pytest.mark.parametrize及mock使用
随机推荐
音视频技术开发周刊 | 255
MXNet对DenseNet(稠密连接网络)的实现
AQS of concurrent programming
mujoco+spinningup进行强化学习训练快速入门
埃拉托斯特尼筛法
Leetcode 113. path sum II
Excel add key run macro
Common methods of arrays
为提高效率使用ParallelStream竟出现各种问题
@wrap 装饰器
Install oh my Zsh
0716RHCSA
2022年下半年软考信息安全工程师如何备考?
Numpy quick start
Install mujoco and report an error: distutils.errors DistutilsExecError: command ‘gcc‘ failed with exit status 1
0715RHCSA
Immortal software in the computer that I don't want to delete all my life
uniapp处理后台传输图片
Excel record macro
In order to improve efficiency, there are various problems when using parallelstream