Description
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
Thinking Process
- Walk through the array, for nums[i], mark nums[nums[i] - 1] as negative. This means, number i exists in the array
- Walk through the array again, whenever it sees a positive number, add index (i + 1) to the output
Code
public class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> res = new LinkedList<>();
int n = nums.length;
for(int i = 0; i < n; i++){
nums[Math.abs(nums[i]) - 1] =
- Math.abs(nums[Math.abs(nums[i]) - 1]);
}
for(int i = 1; i <= n; i++){
if (nums[i - 1] > 0){
res.add(i);
}
}
return res;
}
}
Complexity
- Time is O(n)
- Space is O(1) excluding the space needed for output