1. 程式人生 > >【LeetCode】448. Find All Numbers Disappeared in an Array

【LeetCode】448. Find All Numbers Disappeared in an Array

Problem:

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.

題目:給定一個n位陣列,其中有些數最多出現兩次,找出[1,n]中沒有在陣列中出現的數。

要求,不額外申請空間,且時間複雜度為O(n,其中申請儲存返回值的list物件不計入額外申請空間。


思路:看題覺得陣列內全為正數,可以將數值作為下標,數值為出現標誌。但是不能申請額外空間,只能放棄申請陣列和HashMap等,只能從題目允許的List上操作。

1. 先將陣列排序,這個操作使用內建函式,複雜度應該...(解題時其實我忘考慮了)

2. 遍歷陣列,key為[1,n]中當前出現的數值,如果nums當前的值不等於key或者不比key大1,都視為陣列值出現跳躍,缺少了一個或幾個值

3. 遍歷結束後,要考慮到缺少的數是否為[1,n]中最後幾位。

程式碼:

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> list = new ArrayList<>();
        int len = nums.length;
        if(len==0)
            return list;
        Arrays.sort(nums);
       
        int key = 0;
        for(int i = 0; i < len; i ++){
            if(nums[i]==key||nums[i]==(key+1))
                key=nums[i];
            else{
                key++;
                i--;
                list.add(key);
            }
                
        }
        key = nums[len-1];
        //也許缺少的數為最後幾位
        while(key<len){
            key++;
            list.add(key);
            
        }
            
        return list;
    }

}

此題有毒,排名靠前的都不是遵守規則的解法,於是我也寫了一個

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        List<Integer> list = new ArrayList<>();
        int len = nums.length;
        if(len==0)
            return list;
        int[] arr = new int[len+1];
        for(int i=0;i<len;i++){
            arr[nums[i]]=1; 
        }
        for(int i=1;i<=len;i++)
        {
            if(arr[i]!=1)
                list.add(i);
        }                
        
            
        return list;
    }

}

輕輕鬆鬆....