LC.P448[找到所有数组中消失的数字]

方法一:原地修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
int n = nums.length;
List<Integer> ans = new ArrayList<>();
for (int num : nums) {
int index = (num - 1) % n;
nums[index] += n;
}
for (int i = 0; i < n; ++i) {
if (nums[i] <= n) ans.add(i + 1);
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$

方法二:原地哈希

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
int n = nums.length;
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < n; ++i) {
while (nums[i] != i + 1 && nums[nums[i] - 1] != nums[i]) {
swap(nums, i, nums[i] - 1);
}
}
for (int i = 0; i < n; ++i) {
if (nums[i] != i + 1) ans.add(i + 1);
}
return ans;
}

private void swap(int[] nums, int a, int b) {
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$