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.
應(yīng)該還是基準(zhǔn)排序,主要問題在于如何判斷出現(xiàn)兩次,這里在第二次訪問時可以發(fā)現(xiàn)索引上的數(shù)被置負(fù)了,所以可以判斷出現(xiàn)兩次。
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> result = new ArrayList<>();
for(int i = 0 ;i<nums.length;i++)
{
int index = nums[i]<0?-nums[i]-1: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 ;
}
}