题目
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?
分析
给定包含
方法一:排序法 时间O(nlogn) 空间O(1)
现将序列元素排序,然后一次遍历
方法二:
时间O(n) 空间O(1)
由题意,大小为
AC代码
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;
}//for
return nums.size();
}
};