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
n表示的是最大的值是n,但是数组是从0开始的,所以其实完整的数组是n+1个数字
思路:
1,由小到大排序
2,从0开始,比较与数组中的值是不是相等,若不相等,则表示这里缺少了一个数
3,如果都不缺少,则表示最后一个数字缺少了,则是nums[nums.size()-1]+1
#pragma once
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
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[nums.size() - 1] + 1;
}
};