letecode [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

题目大意

  给定一个包含 0, 1, 2, ..., n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。

理  解:

  将数组元素排序,遍历找到没出现的那个数。

  其他高效解法:下标求和-nums求和。或者下标和nums[i]异或。

代 码 C++:

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

运行结果:

  执行用时 :36 ms, 在所有C++提交中击败了46.89%的用户

  内存消耗 :9.9 MB, 在所有C++提交中击败了8.86%的用户
posted @ 2019-06-14 19:12  lpomeloz  阅读(126)  评论(0编辑  收藏  举报