268. Missing Number序列中遗失的数字

[抄题]:

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

Example 1

Input: [3,0,1]
Output: 2

 

Example 2

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[一个数还不是0]返回0:下次多想想一个数的情况

[思维问题]:

[一句话思路]:

就是for一遍

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

[画图]:

[一刷]:

设置了一个返回值result,不知道怎么初始化。倒不如直接{里面出错结果} + 外面默认正常结果 

[二刷]:

[三刷]:

[四刷]:

[五刷]:

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

[总结]:

直接{里面出错结果} + 外面默认正常结果 

[复杂度]:Time complexity: O(n) Space complexity: O(1 就地for循环)

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

[关键模板化代码]:

[其他解法]:

[Follow Up]:

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

First Missing Positive 越讨论越复杂的一道题

Find the Duplicate Number 快慢指针:好吧可以往这个方向思考

 [代码风格] :

class Solution {
public int missingNumber(int[] nums) {
    
    //ini = sort
    Arrays.sort(nums);
    
    //cc
    if (nums[0] != 0) {
        return 0;
    }

    //for
    for (int i = 0; i < nums.length - 1; i++) {
        if (nums[i + 1] != nums[i] + 1) {
            return nums[i] + 1;
        }
    }

    //return
    return nums.length;
}
}
View Code

 

posted @ 2018-04-17 15:14  苗妙苗  阅读(111)  评论(0编辑  收藏  举报