当前位置:网站首页>【力扣】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开始的。
边栏推荐
- Explain the precision of floating point numbers in detail
- Preparing for the soft test for junior programmers in the second half of 2022
- 嵌入式代码如何进行重构?
- hcip第七天笔记
- Error: cannot find or load main class XXXX
- 刷题-洛谷-P1059 明明的随机数
- Hcip day 8 notes
- Online Learning and Pricing with Reusable Resources: Linear Bandits with Sub-Exponential Rewards: Li
- Install mujoco and report an error: distutils.errors DistutilsExecError: command ‘gcc‘ failed with exit status 1
- Hcip day 6 notes
猜你喜欢

VIM basic operation summary

Concurrent programming - memory model JMM

In order to improve efficiency, there are various problems when using parallelstream

How to solve the problem of taking up too much space when recording and editing videos?

电脑里一辈子都不想删的神仙软件

Based on Baiwen imx6ull_ Ap3216 experiment driven by Pro development board

IM system - some common problems of message streaming

ES6 array de duplication new set()

Preparing for the soft test for junior programmers in the second half of 2022

包管理 apt,dpkg
随机推荐
The simplest solution of the whole network 1045 access denied for user [email protected] (using password:YES)
Mu Changchun, data Research Institute of the central bank: controllable anonymity of digital RMB is an objective need to safeguard public interests and financial security
Azure Devops (XIV) use azure's private nuget warehouse
Talk about your understanding of hashcode and equals methods?
Hcip day 10 notes
Okaleido上线聚变Mining模式,OKA通证当下产出的唯一方式
int数组获取重复数据
Leetcode 113. path sum II
0719RHCSA
Explain the precision of floating point numbers in detail
音视频技术开发周刊 | 255
手写jdbc的使用步骤?
What is your revenue rank among global developers in 2022?
6.27 uniapp project history
Canvas判断内容为空
Canal realizes MySQL data synchronization
埃拉托斯特尼筛法
hcip第七天笔记
Numpy简介和特点(一)
VIM basic operation summary