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
solution:
现将序列元素排序,然后一次遍历i 从0 到n−1 ,若nums[i]!=i ,则i 便是缺失元素,若循环正常结束,则缺失元素为n ;
code:
class Solution {
public:
int missingNumber(vector<int>& nums) {
if (nums.empty())
return 0;
sort(nums.begin(), nums.end());
for (unsigned i = 0; i < nums.size(); ++i)
{
if (nums[i] != i)
return i;
}
return nums.size();
}
};
扫描二维码关注公众号,回复:
6117082 查看本文章