-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashTable 268 Missing Number
38 lines (37 loc) · 1.49 KB
/
HashTable 268 Missing Number
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
solution 1: with O(n) space
def missingNumber(self, nums):
return sum([i for i in range(len(nums)+1)]) - sum(nums)
Solution 2: with O(1) space and use zero_points_to_bit to indicate which key has nums[key] == 0
def missingNumber(self, nums):
extra_bit,zero_points_to_bit = 0,-1
for i in range(len(nums)):
if abs(nums[i]) == len(nums):
extra_bit = 1
if abs(nums[i]) < len(nums):
if nums[abs(nums[i])] == 0:
zero_points_to_bit = abs(nums[i])
nums[abs(nums[i])] = 0 - abs(nums[abs(nums[i])])
if extra_bit == 0:
return len(nums)
for i in range(len(nums)):
if nums[i] > 0 or nums[i] == 0 and zero_points_to_bit == -1:
return i
Solution 3: with O(1) space and replace all keys pointing to zero by using a bigger positive integer to mark
def missingNumber(self, nums):
extra_bit,count = 0,1
for x in nums:
if abs(x) == len(nums):
extra_bit = 1
elif abs(x) > len(nums):
nums[0] = 0 - abs(nums[0])
else:
if nums[abs(x)] == 0:
nums[abs(x)] = len(nums) + count
count += 1
nums[abs(x)] = 0 - abs(nums[abs(x)])
if extra_bit == 0:
return len(nums)
else:
for i in range(len(nums)):
if nums[i] >= 0:
return i