Skip to content

Commit 158fa82

Browse files
committed
no message
1 parent fac3abc commit 158fa82

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

problems/first-missing-positive.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class Solution(object):
2+
def firstMissingPositive(self, nums):
3+
N = len(nums)
4+
5+
if 1 not in nums: return 1
6+
7+
for i, num in enumerate(nums):
8+
if num<=0 or num>N:
9+
nums[i] = 1
10+
11+
for i in xrange(N):
12+
a = abs(nums[i])
13+
14+
if a==N:
15+
nums[0] = -abs(nums[0])
16+
else:
17+
nums[a] = -abs(nums[a])
18+
19+
for i in xrange(1, N):
20+
if nums[i]>0: return i
21+
if nums[0]>0: return N
22+
23+
return N+1
24+
25+
"""
26+
Time: O(N), each num is going to be swap once.
27+
Space: O(1).
28+
29+
For nums with length N, the answer must be in between 1~N+1.
30+
31+
[1] So for number between 1~N, lets put them in the right place.
32+
number 1 will be stored at index 0.
33+
number 2 will be stored at index 1.
34+
...
35+
number n will be stored at index n-1.
36+
37+
38+
[2] Check if any number are not in place.
39+
40+
[3] If all the number are in place, then the ans must be N+1.
41+
"""
42+
class Solution(object):
43+
def firstMissingPositive(self, nums):
44+
N = len(nums)
45+
46+
#[1]
47+
for i in xrange(N):
48+
while 1<=nums[i]<=N and nums[i]!=i+1:
49+
j = nums[i]-1
50+
if nums[i]==nums[j]: break #otherwise they are going to keep swapping infinitely, because one of them is not inplace.
51+
nums[i], nums[j] = nums[j], nums[i]
52+
53+
#[2]
54+
for i in xrange(N):
55+
if nums[i]!=i+1: return i+1
56+
57+
#[3]
58+
return N+1

0 commit comments

Comments
 (0)