来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/missing-number/solution/que-shi-shu-zi-by-leetcode/
描述
给定一个包含 0, 1, 2, …, n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。
示例 1:
输入: [3,0,1]
输出: 2
示例 2:
输入: [9,6,4,2,3,5,7,0,1]
输出: 8
说明:
你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现?
题解
哈希表
常规做法,但需要使用的空间复杂度
class Solution {
public int missingNumber(int[] nums) {
Set<Integer> numSet = new HashSet<>();
for (int num : nums) {
numSet.add(num);
}
int expectedNumCount = nums.length + 1;
for (int number = 0; number < expectedNumCount; number++) {
if (!numSet.contains(number)) {
return number;
}
}
return -1;
}
}
复杂度分析
- 时间复杂度:
。插入操作的时间复杂度都是
,一共插入了
个数,时间复杂度为
。集合的查询操作的时间复杂度同样是
,最多查询
次,时间复杂度为
,因此总的时间复杂度为
。
-
位运算
需要细细品~
class Solution {
public int missingNumber(int[] nums) {
int res = nums.length;
for (int i = 0; i < nums.length; i++) {
res ^= i ^ nums[i];
}
return res;
}
}
复杂度分析
时间复杂度:
。这里假设异或运算的时间复杂度是常数的,总共会进行
次异或运算,因此总的时间复杂度为
。
- 空间复杂度:
。算法中只用到了
的额外空间,用来存储答案。