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
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
思路
由于是从0-N个数之间,只缺少了一个。
一:排序然后两个数之间相减,差值不为1则必有缺少,然后判断左右。
注意:需要考虑边界问题:
class Solution {
public:
int missingNumber(vector<int>& nums) {
if(nums.size()==1)return nums[0]^1;
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size()-1;i++){
if(nums[i+1]-nums[i]!=1){
return i+1;
}
}
if(nums[nums.size()-1]==nums.size())return 0;
return nums.size();
}
};
二:重新定义一个数组,遍历数,然后在数组中置1,然后遍历数组判断存在与否。感觉较慢。
三:遍历一次将所有数相加,然后遍历0-N相加,后者减去前者即可得到。beats 88%
class Solution {
public:
int missingNumber(vector<int>& nums) {
int n =nums.size();
int sum =0,sum1=0;
for(int i=0;i<n;i++){
sum+=nums[i];
sum1+=i;
}
sum1+=n;
return sum1-sum;
}
};