-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path0645.错误的集合.java
73 lines (70 loc) · 1.5 KB
/
0645.错误的集合.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* @lc app=leetcode.cn id=645 lang=java
*
* [645] 错误的集合
*
* https://leetcode.cn/problems/set-mismatch/description/
*
* algorithms
* Easy (40.81%)
* Likes: 293
* Dislikes: 0
* Total Accepted: 92.8K
* Total Submissions: 227.5K
* Testcase Example: '[1,2,2,4]'
*
* 集合 s 包含从 1 到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个数字复制了成了集合里面的另外一个数字的值,导致集合 丢失了一个数字 并且
* 有一个数字重复 。
*
* 给定一个数组 nums 代表了集合 S 发生错误后的结果。
*
* 请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。
*
*
*
* 示例 1:
*
*
* 输入:nums = [1,2,2,4]
* 输出:[2,3]
*
*
* 示例 2:
*
*
* 输入:nums = [1,1]
* 输出:[1,2]
*
*
*
*
* 提示:
*
*
* 2
* 1
*
*
*/
// @lc code=start
class Solution {
public int[] findErrorNums(int[] nums) {
int duplicate = -1;
for (int i = 0; i < nums.length; i++) {
int index = Math.abs(nums[i]) - 1;
if (nums[index] < 0)
duplicate = Math.abs(nums[i]);
else
nums[index] *= -1;
}
int missing = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
missing = ++i;
break;
}
}
return new int[] { duplicate, missing };
}
}
// @lc code=end