题目描述:
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?
使用hash table,以数组的索引为key,value和key相同,即nums[i]=i。
首先遍历一遍数组nums,可能遇到的情况及其处理方法如下:
(1)如果nums[i]=i,直接++i,处理数组中的下一个元素
(2)如果nums[i]!=i,这又可以分为两种情况1)nums[i]<nums.size(),交换nums[i]和nums[nums[i]],即把nums[i]放到正确的位置,然后继续处理新的nums[i];2)nums[i]>=nums.size(),直接++i,即跳过该元素,因为此时数组中没有位置使nums[nums[i]]=nums[i]
然后遍历处理后的数组nums,遇到nums[i]!=i的返回i即为所要求的元素
AC代码如下:
class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
for (int i = 0; i < n;){
if (nums[i] != i){
if (nums[i] < n){
int tmp = nums[nums[i]];
nums[nums[i]] = nums[i];
nums[i] = tmp;
}
else{
++i;
}
}
else{
++i;
}
}
for (int i = 0; i < n; ++i){
if (nums[i] != i) return i;
}
return n;
}
};