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]
Solution:
數(shù)組長度為n志膀,數(shù)組中元素的取值范圍為[1, n]?邻悬,數(shù)組index范圍為[0, n - 1]。也就是說如果數(shù)組元素沒有重復(fù)褒繁,那么對于每個元素k墙懂,都對應(yīng)一個index k-1.
因此我們可以利用這個性質(zhì)堤尾,將出現(xiàn)的元素所對應(yīng)的index上面的元素置負(fù)焊切,用來表示該index所對應(yīng)的元素存在(將nums[index] = - nums[index], 表示index + 1 這個數(shù)是存在的)。遍歷整個數(shù)組對每個元素進行這個操作之后躏筏,再遍歷一遍數(shù)組板丽,如果某個index上的元素nums[index] 非負(fù),則說明該index所對應(yīng)的元素(index + 1)沒有出現(xiàn)過趁尼,則將(index + 1)加入要返回的List埃碱。
// import java.util.*;
public class Solution
{
public List<Integer> findDisappearedNumbers(int[] nums)
{
for(int i = 0; i < nums.length; i ++)
{
int index = Math.abs(nums[i]) - 1;
if(nums[index] > 0)
nums[index] = - nums[index];
}
List<Integer> result = new ArrayList<>();
for(int i = 0; i < nums.length; i ++)
{
if(nums[i] > 0)
result.add(i + 1);
}
return result;
}
}