目录结构
1.题目
给定一个包含 0, 1, 2, ..., n
中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。
示例:
输入: [3,0,1]
输出: 2
输入: [9,6,4,2,3,5,7,0,1]
输出: 8
说明:
你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/missing-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
2.1排序
- 排序后,序列的值和下标一一对应,当下标i和nums[i]不对应时,则i没有出现
- 遍历结束则前n-1个都一一对应,则返回n。
public class Solution268 {
public int missingNumber(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
if (i != nums[i]) {
return i;
}
}
return nums.length;
}
}
- 时间复杂度:
- 空间复杂度:
2.2哈希存储
先将数组中的元素全部放入集合,然后在集合中找出缺失数字。
public class Solution268 {
public int missingNumber(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int n :nums){
set.add(n);
}
for (int i = 0;i<=nums.length;i++){
if (!set.contains(i)){
return i;
}
}
return -1;
}
}
- 时间复杂度:
- 空间复杂度:
2.3位运算
“异或”运算有如下性质:
- 一个数与自身做“异或”运算结果是0;
- 一个数与0做“异或”运算结果是数本身。
故可将0...n的n+1个数做“异或”运算,然后再与数组中的每一个元素进行“异或”运算,数组中的元素均在“异或”运算中出现两次,其结果均为0,故最后的结果即为只出现一次的数字,也就是数组中缺失的数字。
注意result的初始值为nums.length,即n。因为循环中数组的数字均作了异或运算,但序列的取值i只有0到n-1的n个数字。
public class Solution268 {
public int missingNumber(int[] nums) {
int result = nums.length;
for (int i = 0; i < nums.length; i++) {
result ^= i ^ nums[i];
}
return result;
}
}
- 时间复杂度:
- 空间复杂度:
2.4等差数列和
序列实际上是一个首项为0,公差为1,末项为n的等差数列,故可对等差数列求和后减去数组中的所有数字,结果即为缺失数字。
public class Solution268 {
public int missingNumber(int[] nums) {
int sum = (nums.length * (nums.length + 1)) / 2;
for (int n : nums) {
sum -= n;
}
return sum;
}
}
- 时间复杂度:
- 空间复杂度: