-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_missing_positive_number_in_list.py
56 lines (41 loc) · 1.18 KB
/
find_missing_positive_number_in_list.py
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
"""
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
"""
def find_missing_number(nums):
n = len(nums)
sum = n * (n+1) // 2
diff = 0
for i in nums:
if i > 0:
diff += i
return sum - diff
def find_missing_number_maxmin(nums):
max_num = max(nums)
min_num = 2**32
# find min number greater than 0
for i in nums:
if i < min_num and i >= 0:
min_num = i
for i in range(min_num, max_num + 1):
if i not in nums:
return i
def find_missing_number_kaz(nums):
nums.sort(reverse=True)
print(nums)
for i in nums:
mn = min(nums)
if mn < 0:
nums.pop()
print(mn)
if mn == 1 or mn == 0:
x = mn + 1
if x in nums:
x = x + 1
else:
x = mn - 1
return x
nums = [3, 5]
print(find_missing_number(nums))
nums = [3, 4, -1, 1]
print(find_missing_number_kaz(nums))