【每日一题-leetcode】448.找到全部数组中的消失的数字

448.找到全部数组中的消失的数字
  1. 找到全部数组中消失的数字

难度简单382java

给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另外一些只出现一次。数组

找到全部在 [1, n] 范围之间没有出如今数组中的数字。app

您能在不使用额外空间且时间复杂度为O(n)的状况下完成这个任务吗? 你能够假定返回的数组不算在额外空间内。ide

示例:spa

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

输出:
[5,6]

时间复杂度O(n)code

空间复杂度O(1)it

//将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;
    }

鸽巢定理class

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];
            }
        }
相关文章
相关标签/搜索