您的位置:首页 > 其它

268. Missing Number

2017-07-16 16:03 183 查看
1.题目

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

For example,

Given nums = 
[0, 1, 3]
 return 
2
.

Note:

Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

2.分析

   这道题真的蛮easy的,我想说的是解题思路,很多题目解题都可以采用类似的思路。借助于一个辅助数组,长度为输入的数据长度加1,通过O(n)时间遍历并记录数据,再遍历标记的辅助数组,得出最后的那个数据。

3.解题

   public class Solution {

    public int missingNumber(int[] nums) {

        // 借助于一个辅助的数组空间

        if(nums==null||nums.length==0){

            return -1;

        }

        int len = nums.length;

        int number = -1;

        int[] result = new int[len+1];

        // 记录存在的数  

        for(int i=0;i<len;i++){

            result[nums[i]] = 1;

        }

        // O(n)时间找出不存在的那个数

        for(int i=0;i<len+1;i++){

            if(result[i]!=1){

                number = i;

                break;

            }

        }

        return number;

    }

}

4.总结

   这道题,虽然很简单,不要几分钟就能解决,但是其中的解题思想在其他题中可以予以借鉴。利用空间换取时间,如果采用暴力破解等方法用时间换取空间解题,当然能得到结果,但是时间效率低,另外对于测试用例全面的,很难A过吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: