给定一个包含 0, 1, 2, …, n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。
示例 1:
输入: [3,0,1]
输出: 2
示例 2:
输入: [9,6,4,2,3,5,7,0,1]
输出: 8
说明:
你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现?
思路:解决这道题我首先将数字排序,然后利用前后如果不缺少数字的话后面那个数减去前面那个数的差应该为1,如果不为一的话说明这两个数中间缺少一个数。做这道的题的不足在于忘记考虑如果缺了0和缺了最后一个数字的情况,所以这道题分为三种请款来考虑。
class Solution {
public int missingNumber(int[] nums) {
if(nums.length == 0) return -1;
Arrays.sort(nums);
int a = 0;
if(nums[0] != 0) return 0;//第一种情况,缺少第一个数字0
for(int i = 0; i < nums.length-1; i++){//第二种情况,缺少中间的某个数字
if(nums[i+1] - nums[i] == 1){
continue;
}else{
return nums[i]+1;
}
}
return nums[nums.length-1]+1;//第三种情况,缺少最后一个数字
}
}