LeetCode刷题笔记 448. 找到所有数组中消失的数字

题目描述

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

找到所有在 [1, n] 范围之间没有出现在数组中的数字。

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

示例:
输入:
[4,3,2,7,8,2,3,1]
输出:
[5,6]

总结

对于数组的题,下标法可以解决一些问题

Sample Code 1

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

Sample Code 2

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        for(int i = 0; i < nums.length; ) {
            int loc = nums[i];
            if(loc == -1 || i == loc-1) {
                i++;
                continue;
            }
            if(nums[loc-1] == loc) {
                nums[i] = -1;
                i++;
                continue;
            }
            int temp = nums[loc-1];
            nums[loc-1] = nums[i];
            nums[i] = temp;
        }
        
        List<Integer> ans = new ArrayList<>();
        for(int i = 0; i < nums.length; i++){
            if(nums[i] == -1) ans.add(i+1);        
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/XIIV13/article/details/93749129