Given an integer array with a range of 1 ≤ a[i] ≤ n (n = array size), some elements in the array appear twice, and some only appear once.
Find all the numbers in the range [1, n] that do not appear in the array.
Can you accomplish this task without using extra space and the time complexity is O(n)? You can assume that the returned array is not included in the extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
Source: LeetCode
Link: https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array
Method: In-situ modification
Iterate through each element of the input array once. The element at the index position of |nums[i]|-1
will be marked as a negative number. That is, nums[∣nums[i]∣−1]×−1 . Then traverse the array. If the current array element nums[i] is a positive number, it means that the number i + 1 has not appeared.
public static List<Integer> findDisappearedNumbers(int[] nums) {
for (int i = 0; i < nums.length; i++) {
if (nums[Math.abs(nums[i]) - 1] > 0) nums[Math.abs(nums[i]) - 1] *= -1;
}
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) list.add(i + 1);
}
return list;
}