forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdusunax.py
More file actions
63 lines (48 loc) · 1.16 KB
/
dusunax.py
File metadata and controls
63 lines (48 loc) · 1.16 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
'''
# 268. Missing Number
A. iterative approach: sort the array and find the missing number.
B. XOR approach: use XOR to find the missing number.
- a ^ a = 0, a ^ 0 = a
## Time and Space Complexity
### A. Iterative Approach
```
TC: O(n log n)
SC: O(1)
```
#### TC is O(n):
- sorting the array. = O(n log n)
- iterating through the array just once to find the missing number. = O(n)
#### SC is O(1):
- no extra space is used. = O(1)
### B. XOR Approach
```
TC: O(n)
SC: O(1)
```
#### TC is O(n):
- iterating through the array just once to find the missing number. = O(n)
#### SC is O(1):
- no extra space is used. = O(1)
'''
class Solution:
'''
A. Iterative Approach
'''
def missingNumberIterative(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
for i in range(n):
if nums[i] != i:
return i
return n
'''
B. XOR Approach
'''
def missingNumberXOR(self, nums: List[int]) -> int:
n = len(nums)
xor_nums = 0
for i in range(n + 1):
if i < n:
xor_nums ^= nums[i]
xor_nums ^= i
return xor_nums