Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.
Input: [3,0,1]
Output: 2
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
首先我们通过输入的向量可以得到n
的大小,将原数组排序之后进行遍历,若遍历的下标和数组中的元素不等时,表明此下标即为缺失的值。
class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = nums.size() + 1;
int max = n;
sort(nums.begin(), nums.end());
for(int i = 0; i < max; ++i) {
if(i != nums[i]) {
return i;
}
}
}
};