leetcode刷题,总结,记录,备忘 268

leetcode268

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?

不是很难,多琢磨几次就ok了,不详细说明了,详见代码。

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        if (nums.size() == 1){
            if (nums[0] == 0) {
                return nums[0]+1;
            } else {
                return 0;
            }
        }
        sort(nums.begin(), nums.end());
        for (vector<int>::iterator it = nums.begin(); it != nums.end() - 1; ++it) {
            if (*it + 1 != *(it+1)) {
                return *it + 1;
            }
        }
        if (nums[0] != 0) {
            return 0;
        } else {
            return nums[nums.size()-1] + 1;
        }
    }
};


你可能感兴趣的:(leetcode刷题,总结,记录,备忘 268)