18丢失的数字
一、题目
给定一个包含 [0, n] 中 n 个数的数组 nums ,找出 [0, n] 这个范围内没有出现在数组中的那个数。
链接:https://leetcode-cn.com/problems/missing-number/solution/diu-shi-de-shu-zi-by-leetcode-solution-naow/
来源:力扣(LeetCode)
二、示例
示例①
输入:nums = [3,0,1]
输出:2
解释:n = 3,因为有 3 个数字,所以所有的数字都在范围 [0,3] 内。2 是丢失的数字,因为它没有出现在 nums 中。
示例②
输出:2
解释:n = 2,因为有 2 个数字,所以所有的数字都在范围 [0,2] 内。2 是丢失的数字,因为它没有出现在 nums 中。
三、代码实现
排序
public static int missingNumber(int[] nums){
int length = nums.length;
Arrays.sort(nums);
for (int i = 0;i < length;i++){
if (i != nums[i]){
return i;
}
}
return length;
}
第一个就想到了这个
哈希表
public static int missingNumberByHashTable(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;
把数组中的数存入集合,通过循环得出集合中没有的数
位运算
public static int missingNumberByBitArithmetic(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;
}
原来是异或基于二位制的运算,总算搞懂了,但什么原理不是很懂,以后遇到了深入了解
数学
public static int missingNumberByMath(int[] nums){
int n = nums.length;
int total = n * (n + 1) /2;
int arrsum = 0;
for (int i = 0;i < nums.length;i++){
arrsum += nums[i];
}
return total - arrsum;
}
高斯求和公式: total = [n(n+1)]/2 数组的元素和为arrsum,缺失的元素即为total - arrsum
数学nb
四、复杂度分析
排序
- 时间复杂度:O*(nlog*n)
- 空间复杂度:O*(nlog*n)
哈希表
- 时间复杂度:O(n)
- 空间复杂度:O(n)
位运算
- 时间复杂度:O(n)
- 空间复杂度:O(1)
数学
- 时间复杂度:O(n)
- 空间复杂度:O(1)