• 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
  • 相关阅读:
    JavaSE基础(七)--Java流程控制语句之switch case 语句
    JavaSE基础(六)--Java流程控制语句之条件语句
    JavaSE基础(五)--Java运算符
    搭建seafile文档系统
    centos7 DHCP搭建双机热备 集群
    centos7安装DHCP后启动不了的问题解决方法
    思科ASA防火墙精华配置总结
    思科常用命令大全
    浅谈集线器、路由器、交换机、网关的作用与区别
    交换机端口镜像及其工作原理
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8870388.html
Copyright © 2020-2023  润新知