zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    centos7 安装 tesseract4.1
    08 图的数据结构和算法
    07 树形结构及其算法
    05 数组与链表算法
    06 堆栈与队列算法
    04 查找与哈希算法
    03 排序算法
    javascript 标签轮播
    tomcat URI get 参数中文传到后台 乱码 URIEncoding
    javascript 标签切换
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8870388.html
Copyright © 2011-2022 走看看