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.

應(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 ;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容