题目
给定一个包含 0, 1, 2, …, n 中 n 个数的序列,找出 0 … n 中没有出现在序列中的那个数。
示例 1:
输入: [3,0,1]
输出: 2
示例 2:
输入: [9,6,4,2,3,5,7,0,1]
输出: 8
Constraints:
n == nums.length
1 <= n <= 10^4
0 <= nums[i] <= n
All the numbers of nums are unique.
Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?
Solution
Change original list
Go through the original list, use the current value as the index, and multiply the value under the new index by -1
. And then go through the list, the positive number’s index is the missing value.
One special case is, 0 * -1 = 0
, so use another map to store 0
.
Time complexity:
o
(
n
)
o(n)
o(n)
Space complexity:
o
(
1
)
o(1)
o(1)
Bit manipulation
Solved after help.
Because x ^ x = 0
, so we can calculate the xor from 0
to n
, and then xor all the numbers in the list. And the result will be our missing value.
To simply, we can just xor the index and value at the same time, and then xor n
at the end.
Time complexity:
o
(
n
)
o(n)
o(n)
Space complexity:
o
(
1
)
o(1)
o(1)
Similarly, we can do a sum… Sum from 0
to n
first, and then subtract every element in the nums
代码
Change original list
class Solution:
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)
special_cases = {0: False}
for i in range(n):
new_index = nums[i]
if new_index < 0:
new_index *= -1
if new_index < n:
if nums[new_index] == 0:
special_cases[0] = True
else:
nums[new_index] *= -1
for i in range(n):
if nums[i] > 0:
return i
elif nums[i] == 0 and not special_cases[0]:
return i
return n
Bit manipulation
class Solution:
def missingNumber(self, nums: List[int]) -> int:
xor = 0
for i in range(len(nums)):
xor ^= i ^ nums[i]
return xor ^ len(nums)