原地哈希
# 448. 找到所有数组中消失的数字 (opens new window)
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> res = new ArrayList<>();
int n = nums.length;
for(int i=0;i<n;i++){
while(nums[nums[i]-1]!=nums[i]){
swap(nums,i,nums[i]-1);
}
}
for(int i=0;i<n;i++){
if(nums[i]!=i+1){
res.add(i+1);
}
}
return res;
}
void swap(int[] nums,int i,int j){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 03. 数组中重复的数字 (opens new window)
class Solution {
public int findRepeatDocument(int[] nums) {
int n = nums.length;
// 把nums[i]放在i位置上
for(int i=0;i<n;i++){
if(nums[i]!=nums[nums[i]]){
swap(nums,i,nums[i]);
}
}
for(int i=0;i<n;i++){
if(nums[i]!=i){
return nums[i];
}
}
return -1;
}
void swap(int[] nums,int i,int j){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 442. 数组中重复的数据 (opens new window)
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> res = new ArrayList<>();
int n = nums.length;
for(int i=0;i<n;i++){
while(nums[nums[i]-1] != nums[i]){
swap(nums,i,nums[i]-1);
}
}
for(int i=0;i<n;i++){
if(nums[i]-1 != i){
res.add(nums[i]);
}
}
return res;
}
void swap(int[] nums,int i,int j){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 41. 缺失的第一个正数 (opens new window)
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
for(int i=0;i<n;i++){
while(nums[i]>0 && nums[i]<=n && nums[nums[i]-1]!=nums[i]){
swap(nums,nums[i]-1,i);
}
}
for(int i=0;i<n;i++){
if(nums[i]!=i+1){
return i+1;
}
}
return n+1;
}
void swap(int[] nums,int i,int j){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21