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:
數組長度為n,數組中元素的取值范圍為[1, n]?,數組index范圍為[0, n - 1]。也就是說如果數組元素沒有重復,那么對于每個元素k,都對應一個index k-1.
因此我們可以利用這個性質,將出現的元素所對應的index上面的元素置負,用來表示該index所對應的元素存在(將nums[index] = - nums[index], 表示index + 1 這個數是存在的)。遍歷整個數組對每個元素進行這個操作之后,再遍歷一遍數組,如果某個index上的元素nums[index] 非負,則說明該index所對應的元素(index + 1)沒有出現過,則將(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;
}
}