当前位置:网站首页>【力扣】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开始的。
边栏推荐
猜你喜欢

【GCN-CTR】DC-GNN: Decoupled GNN for Improving and Accelerating Large-Scale E-commerce Retrieval WWW22

JS Array indexOf includes sort() 冒号排序 快速排序 去重和随机样本 random

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

GCD details

0713RHCSA

二叉树基本知识

刷题-洛谷-P1150 Peter的烟

Redis visualizer RDM installation package sharing

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

Nodejs link MySQL error: Er_ NOT_ SUPPORTED_ AUTH_ MODEError: ER_ NOT_ SUPPORTED_ AUTH_ MODE
随机推荐
Leetcode 113. 路径总和 II
包管理 apt,dpkg
Based on Baiwen imx6ull_ Ap3216 experiment driven by Pro development board
0717RHCSA
The interviewer asked me: how much do you know about MySQL's storage engine?
C#基础学习(二十三)_窗体与事件
Excel录制宏
arm架构移植alsa-lib和alsa-utils一路畅通
备战2022 CSP-J1 2022 CSP-S1 初赛 视频集
Canvas judgment content is empty
ES6 array de duplication new set()
Mutex lock, spin lock, read-write lock... Clarify their differences and applications
Error: cannot find or load main class XXXX
Prepare for 2022 csp-j1 2022 csp-s1 preliminaries video set
Serious [main] org.apache.catalina.util.lifecyclebase Handlesubclassexception initialization component
IM system - some common problems of message streaming
hcip第十天笔记
How to refactor embedded code?
Leetcode 113. path sum II
hcip第八天笔记