LeetCode448找到所有数组中消失的数字

94 阅读1分钟

🍀 找出所有数组中消失的数字

描述:

# 给你一个含 n 个整数的数组 nums ,其中 nums[i] 在区间 [1, n] 内。请你找出所有在 [1, n] 范围内但没有出现在 nums 中的数字,并以数组的形式返回结果。

 

示例 1:

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

输入:nums = [1,1]
输出:[2]
 

提示:

n == nums.length
1 <= n <= 105
1 <= nums[i] <= n
进阶:你能在不使用额外空间且时间复杂度为 O(n) 的情况下解决这个问题吗? 你可以假定返回的数组不算在额外空间内。

思考:

​ 很简单啊!计时器完美解决,创造对应长度的数组,把两个数组一一映射,最后找到没有被标记的数放在结果数组里即可!

实现:

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {

        int[] counter = new int[nums.length + 1];
        List<Integer> res = new ArrayList<>();


        for (int i = 0; i < nums.length; i++) {
            // 在计数器数组做标记
            counter[nums[i]] = 1;
        }

        for (int i = 1; i < counter.length; i++) {
            // 找出未标记的即可
            if (counter[i] != 1){
                res.add(i);
            }
        }

        return res;

    }
}

测试一下!

image.png

大佬的代码:

# 官方给出的代码对应的解释

# 由题目知,nums数组中一定存在重复的数字,nums中的数字一定属于[1,n]。 在第一个for循环中更改了nums的部分值!!!!!!!对于nums[i]的值改变次数是由出现了多少次i+1值。数i若存在则下标是i-1这个位置的数一定大于n,被改变了!!!!!!!eg:[4,3,2,7,8,2,3,1]在第一个for循环结束后是[12,19,18,15,8,2,11,9] n=8nums[1]=3被改变了2次得到19即出现了两次2,nums[2]=2被改变了2次变成了18即出现了两次3.

# 取余保证了重复出现的数只会更改一个位置的值。
class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        int n = nums.length;
        for (int num : nums) {
            int x = (num - 1) % n;
            nums[x] += n;
        }
        List<Integer> ret = new ArrayList<Integer>();
        for (int i = 0; i < n; i++) {
            if (nums[i] <= n) {
                ret.add(i + 1);
            }
        }
        return ret;
    }
}