LeetCode OJ:Missing Number (丢失的数)

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?

题目实际上很简单,就是要求求出一段o-n中缺了一个数的数列中找出缺失的那个,我一开始的想法是这样的:

 1 class Solution {
 2 public:
 3     int missingNumber(vector<int>& nums) {
 4         int sz = nums.size();
 5         for (int i = 0; i < sz - 1; ++i){
 6             if (nums[i] != nums[i + 1])
 7                 return nums[i + 1];
 8         }
 9         return nums[sz - 1] + 1;
10     }
11 };

代码很简单,就是遍历比较而已。但是很明显的,不太符合题目对于常数项空间复杂度的要求,出去翻了翻答案,别人家的小孩是这样写的:

 1 class Solution {
 2 public:
 3     int missingNumber(vector<int>& nums) {
 4         int sz = nums.size();
 5         int total = (sz + 1)*sz / 2;
 6         for (int i = 0; i < sz; ++i){
 7             total -= nums[i];
 8         }
 9         return total;
10     }
11 };

这种被吊打的感觉,有点像高斯当时算随手算出5050吊打同伴小孩的情况。

java代码如下:

public class Solution {
    public int missingNumber(int[] nums) {
        int sum = nums.len * (nums.len + 1)/2; //length大小是n-1
        for(int i = 0; i < nums.length; ++i){
            sum -= nums[i];
        }
        return sum;
    }
}

 

posted @ 2015-10-10 20:50  eversliver  阅读(281)  评论(0编辑  收藏  举报