【每日一題-leetcode】448.找到所有數組中的消失的數字

448.找到所有數組中的消失的數字

  1. 找到所有數組中消失的數字

難度簡單382

給定一個範圍在 1 ≤ a[i] ≤ n ( n = 數組大小 ) 的 整型數組,數組中的元素一些出現了兩次,另一些只出現一次。

找到所有在 [1, n] 範圍之間沒有出現在數組中的數字。

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

示例:

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

輸出:
[5,6]

時間複雜度O(n)

空間複雜度O(1)

//將nums中的數放到對應的下標中去。
    public List<Integer> findDisappearedNumbers(int[] nums) {
        if(nums == null || nums.length == 0){
            return new ArrayList<Integer>();
        }
         
        int [] arr = new int [nums.length+1];
        for(int i=0;i<nums.length;i++){
            arr[nums[i]] = nums[i];
        }

        List<Integer> res = new ArrayList<>();
        for(int i=1;i<arr.length;i++){
            if(arr[i] == 0 ){
                res.add(i);
            }
        }
        return res;
    }

鴿巢定理

		public List<Integer> findDisappearedNumbers(int[] nums) {
            if(nums == null || nums.length == 0){
                return new ArrayList<>();
            }
    
            int l = nums.length;
            for(int i=0;i<l;i++){
                while( nums[i] != nums[nums[i]-1] ){
                    swap(nums,i,nums[i]-1);
                }
            }
            List<Integer> res = new ArrayList<>();
            for(int i=0;i<l;i++){
                if(nums[i]!=i+1){
                    res.add(i+1);
                }
            }
            return res;
        }
    
    
        public void swap(int [] nums,int a,int b){
            if(a!=b){
                nums[a] = nums[a] ^ nums[b];
                nums[b] = nums[a] ^ nums[b];
                nums[a] = nums[a] ^ nums[b];
            }
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章