Find All Numbers Disappeared in an Array
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]
Hint
Train of Thought
brute force: 用一个set, 把出现过的就加进去, 最后再扫一遍1-n, 得到没在set里出现过的
No extra space: Make the value at the index of nums[i] to its negative value, so when we iterate the array, the indices that have positive value are not in the array
Code
public class Solution {
public int[] findDisappearedNumbers(int[] nums) {
int count=0;
for(int i=0;i<nums.length;i++) {
if(nums[Math.abs(nums[i])-1]>0){
int val=-nums[Math.abs(nums[i])-1];
nums[Math.abs(nums[i])-1]=val;
}else {
count++;
}
}
int[] result=new int[count];
int index=0;
for(int i=0;i<nums.length;i++) {
if(nums[i]>0) {
result[index]=i+1;
index++;
}
}
return result;
}
}