6.5 丢失的数字【268】
6.5.1 题目描述
给定一个包含 [0, n]
中 n
个数的数组 nums
,找出 [0, n]
这个范围内没有出现在数组中的那个数。
6.5.2 方法一:排序
class Solution {
public int missingNumber(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
for (int i = 0; i < n; i++) {
if (nums[i] != i) {
return i;
}
}
return n;
}
}
复杂度分析
-
时间复杂度:O(nlogn),其中 n 是数组 nums 的长度。排序的时间复杂度是 O(nlogn),遍历数组寻找丢失的数字的时间复杂度是 O(n),因此总时间复杂度是 O(nlogn)。
-
空间复杂度:O(logn),其中 n 是数组 nums 的长度。空间复杂度主要取决于排序的递归调用栈空间。
6.5.3 方法二:哈希集合
使用哈希集合,可以将时间复杂度降低到 O(n)。
首先遍历数组 nums,将数组中的每个元素加入哈希集合,然后依次检查从 0 到 n 的每个整数是否在哈希集合中,不在哈希集合中的数字即为丢失的数字。由于哈希集合的每次添加元素和查找元素的时间复杂度都是 O(1),因此总时间复杂度是 O(n)。
class Solution {
public int missingNumber(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
int n = nums.length;
for (int i = 0; i < n; i++) {
set.add(nums[i]);
}
int missing = -1;
for (int i = 0; i <= n; i++) {
if (!set.contains(i)) {
missing = i;
break;
}
}
return missing;
}
}
复杂度分析
-
时间复杂度:O(n),其中 n 是数组 nums 的长度。遍历数组 nums 将元素加入哈希集合的时间复杂度是 O(n),遍历从 0 到 n 的每个整数并判断是否在哈希集合中的时间复杂度也是 O(n)。
-
空间复杂度:O(n),其中 n 是数组 nums 的长度。哈希集合中需要存储 n 个整数。
6.5.4 方法三:位运算
class Solution {
public int missingNumber(int[] nums) {
int xor = 0;
int n = nums.length;
for (int i = 0; i < n; i++) {
xor ^= nums[i];
}
for (int i = 0; i <= n; i++) {
xor ^= i;
}
return xor;
}
}
复杂度分析
- 时间复杂度:O(n),其中 nn 是数组 nums 的长度。需要对 2n+1 个数字计算按位异或的结果。
- 空间复杂度:O(1)。
6.5.5 方法四:数学
将从 0 到 n 的全部整数之和记为 total,根据高斯求和公式,有:
total = ∑ i = 1 n = n ( n + 1 ) 2 \textit{total} = \sum_{i=1}^n = \dfrac{n(n+1)}{2} total=∑i=1n=2n(n+1)
将数组 nums 的元素之和记为 arrSum,则 arrSum 比 total 少了丢失的一个数字,因此丢失的数字即为 total 与 arrSum 之差。
class Solution {
public int missingNumber(int[] nums) {
int n = nums.length;
int total = n * (n + 1) / 2;
int arrSum = 0;
for (int i = 0; i < n; i++) {
arrSum += nums[i];
}
return total - arrSum;
}
}
复杂度分析
- 时间复杂度:O(n),其中 n 是数组 nums 的长度。需要 O(1) 的时间计算从 0 到 n 的全部整数之和以及需要 O(n) 的时间计算数组 nums 的元素之和。
- 空间复杂度:O(1)。
6.5.6 my answer—排序/set集合
class Solution {
// set集合
public int missingNumber(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
for (int i = 0; i < nums.length; i++) {
if(!set.contains(i))return i;
}
return nums.length;
}
// 排序
public int missingNumber(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
if(nums[i] != i)return i;
}
return nums.length;
}
}