448. Find All Numbers Disappeared in an Array

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上面的元素置負,用來表示該index所對應(yīng)的元素存在(將nums[index] = - nums[index], 表示index + 1 這個數(shù)是存在的)。遍歷整個數(shù)組對每個元素進行這個操作之后,再遍歷一遍數(shù)組,如果某個index上的元素nums[index] 非負,則說明該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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容