448. Find All Numbers Disappeared in an Array 寻找有界数组[1,n]中的缺失数

[抄题]:

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.

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

不知道怎么去除重复

[一句话思路]:

nums[nums[i] -1] = -nums[nums[i]-1] 每个数字处理一次。没有被处理的正数就是被前面的挤兑了。背吧

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 要做index的数必须取绝对值

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

没有被处理的正数就是被前面的挤兑了.这题[1,n]两端必有的情况太特殊

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

442. Find All Duplicates in an Array 出现两次的:还是考数学啊

 [代码风格] :

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        //ini
        List<Integer> result = new ArrayList<Integer>();
        
        //cc
        if (nums == null || nums.length == 0) {
            return result;
        }
        
        //-1
        for (int i = 0; i < nums.length; i++) {
            int val = Math.abs(nums[i]) - 1;//true
            if (nums[val] > 0) {
                nums[val] = - nums[val];
            }
        }
        
        //check
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) {
                result.add(i + 1);
            }
        }
        
        //return
        return result;
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/8870388.html