448. Find All Numbers Disappeared in an Array (陣列中找到所有消失的數字)

題目

Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.

給定一個包含n個整數的陣列nums,其中nums[i]的範圍為[1, n],返回一個陣列,其中包含範圍[1, n]內未在nums中出現的所有整數。


Example 1

1
2
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]

Example 2

1
2
Input: nums = [1,1]
Output: [2]

Constraints:

  • n == nums.length
  • 1 <= n <= 105
  • 1 <= nums[i] <= n

我的解題

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> result = new ArrayList<>();

for (int i = 0; i < nums.length; i++) {
int index = Math.abs(nums[i]) - 1;
if (nums[index] > 0) {
nums[index] = -nums[index];
}
}

for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
result.add(i + 1);
}
}

return result;
}
}