力扣(LeetCode)448

題目地址:
https://leetcode-cn.com/probl...
題目描述:
給定一個範圍在 1 ≤ a[i] ≤ n ( n = 數組大小 ) 的 整型數組,數組中的元素一些出現了兩次,另外一些只出現一次。java

找到全部在 [1, n] 範圍之間沒有出如今數組中的數字。數組

您能在不使用額外空間且時間複雜度爲O(n)的狀況下完成這個任務嗎? 你能夠假定返回的數組不算在額外空間內。app

示例:code

輸入:
[4,3,2,7,8,2,3,1]leetcode

輸出:
[5,6]get

解答:
對原數組作映射,把數字i(i>=1,i<=n)映射到原數組的nums[i-1]上,使得nums[i-1]爲-1。
而後再掃描一遍數組,若是numsj不爲-1,那麼j+1就不存在!
java ac代碼:io

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        
        List<Integer>ans = new ArrayList(nums.length);
        for(int i = 0;i < nums.length;i++)
        {
            
            int loc = nums[i]-1;
            if(loc != -2)
            while(nums[loc] != -1){
            int temp = nums[loc]-1;    
            nums[loc] = -1;
            loc = temp;
            }
            
        }
        for(int i = 0;i < nums.length;i++)
            if(nums[i] != -1)
                ans.add(i+1);
        return ans;
        
    }
}
相關文章
相關標籤/搜索