File tree Expand file tree Collapse file tree 1 file changed +31
-5
lines changed Expand file tree Collapse file tree 1 file changed +31
-5
lines changed Original file line number Diff line number Diff line change 1
1
def first_missing_positive (nums ):
2
2
"""
3
- :type nums: List[int]
4
- :rtype: int
3
+ Find the first missing positive integer in a list of integers.
4
+
5
+ This algorithm sorts the array by making swaps
6
+ and ignoring elements that are greater than the length
7
+ of the array or negative.
8
+
9
+ If the element is equal to the current index (start) then
10
+ it is already in place.
11
+
12
+ If the element is < 0 or > len() or a duplicate, then pull
13
+ in the last element.
14
+
15
+ Otherwise swap the current element into place with the
16
+ element that is occupying it's appropriate place. Do this
17
+ until the current value is the correct one for its place or
18
+ the start and end have swapped.
19
+
20
+ Args:
21
+ nums: list of integers
22
+
23
+ Returns:
24
+ The first integer greater than 0 that is not
25
+ present in the input list.
5
26
"""
6
27
start = 0
7
28
end = len (nums ) - 1
8
29
while start <= end :
9
- i = nums [start ] - 1
30
+ i = nums [start ] - 1
31
+ # if this element is in position
10
32
if i == start :
11
33
start += 1
34
+ # if the element is negative or out of bounds
35
+ # or a duplicate that is already sorted swap the
36
+ # current element into the oob and dec the end
12
37
elif i < 0 or i > end or nums [start ] == nums [i ]:
13
38
nums [start ] = nums [end ]
14
39
end -= 1
40
+ # swap the element to where it should be
15
41
else :
16
- nums [start ] = nums [i ]
17
- nums [ i ] = i + 1
42
+ nums [start ], nums [ i ] = nums [i ], nums [ start ]
43
+
18
44
return start + 1
You can’t perform that action at this time.
0 commit comments