题目描述:
给定一个包含 0, 1, 2, …, n 中 n 个数的序列,找出 0 … n 中没有出现在序列中的那个数。
示例1
输入: [3,0,1]
输出: 2
示例2
输入: [9,6,4,2,3,5,7,0,1]
输出: 8
这里先来说下思路:
- 排序后查找不相连的数字
因为给定的数组中数字的范围只会存在于【0,ArrayLength】之中 所以排序后不想连两个数字的中间数即为缺失数字
这个方法我一开始没想到,是看题解想到的直接附上leetcode代码
class Solution {
public int missingNumber(int[] nums) {
Arrays.sort(nums);
// 判断 n 是否出现在末位
if (nums[nums.length-1] != nums.length) {
return nums.length;
}
// 判断 0 是否出现在首位
else if (nums[0] != 0) {
return 0;
}
// 此时缺失的数字一定在 (0, n) 中
for (int i = 1; i < nums.length; i++) {
int expectedNum = nums[i-1] + 1;
if (nums[i] != expectedNum) {
return expectedNum;
}
}
// 未缺失任何数字(保证函数有返回值)
return -1;
}
}
- 将数组保存在另一个数组中 下标和值对应,然后遍历该数组 寻找值为零的下标并返回
值得注意的一点:新建数组的长度应为原数组长度+1
代码如下:
class Solution {
public int missingNumber(int[] nums) {
int[] results = new int[nums.length + 1];
for(int i : nums) results[i] = i;
for(int i = 0; i < results.length; i++) {
if(results[i] == 0 && i != 0) {
return i;
}
}
return 0;
}
}