问题:丢失的数字
给定一个包含 [0, n] 中 n 个数的数组 nums ,找出 [0, n] 这个范围内没有出现在数组中的那个数。
示例 1:
输入:nums = [3,0,1]
输出:2
解释:n = 3,因为有 3 个数字,所以所有的数字都在范围 [0,3] 内。2是丢失的数字,因为它没有出现在 nums 中。
示例 2:
输入:nums = [0,1]
输出:2
解释:n = 2,因为有 2 个数字,所以所有的数字都在范围 [0,2] 内。2是丢失的数字,因为它没有出现在 nums 中。
示例 3:
输入:nums = [9,6,4,2,3,5,7,0,1]
输出:8
解释:n = 9,因为有 9个数字,所以所有的数字都在范围 [0,9] 内。8 是丢失的数字,因为它没有出现在 nums 中。
示例 4:
输入:nums = [0]
输出:1
解释:n = 1,因为有 1 个数字,所以所有的数字都在范围 [0,1] 内。1是丢失的数字,因为它没有出现在 nums 中。
思路一:排序
- 对数组元素进行排序
- 找出前后差值不为1的元素
- 该元素后一个即为丢失的数字
**特殊情况:**所有元素均连续,且从0开始时,丢失的元素应该为n。
代码:
class Solution {
public int missingNumber(int[] nums) {
Arrays.sort(nums);
int result = 0;
for(int i=1; i<nums.length; i++){
if(nums[i]-nums[i-1] != 1)
result = nums[i-1] + 1;
}
if((result == 0) && (nums[0]==0))
result = nums[nums.length-1]+1;
return result;
}
}
思路二:数学法
- 已知 1 + 2 + 3 + ⋯ + n = n ( n + 1 ) 2 1+2+3+\cdots+n=\frac{n(n+1)}{2} 1+2+3+⋯+n=2n(n+1),故 [ 0 , n ] [0,n] [0,n]范围内所有整数的和为 t o t a l = n ( n + 1 ) 2 total=\frac{n(n+1)}{2} total=2n(n+1)
- 对nums内的所有元素求和sum
- 故丢失的数字即为: t o t a l − s u m total-sum total−sum
class Solution {
public int missingNumber(int[] nums) {
int n = nums.length;
int total = n*(n+1)/2;
int sum = 0;
for(int i=0; i<n; i++){
sum += nums[i];
}
return total-sum;
}
}