forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
41_First_Missing_Positive
101 lines (74 loc) · 2.16 KB
/
41_First_Missing_Positive
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
Leetcode 41: First Missing Positive
Detailed video Explanation: https://youtu.be/L1u-R_s2Mok
======================================
C++:
----
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
bool contains_one = false;
for(int x: nums){
if(x == 1){
contains_one = true;
break;
}
}
if(!contains_one) return 1;
int n = nums.size();
if(n == 1) return 2;
for(int i = 0; i < n; ++i)
if(nums[i] <= 0 || nums[i] > n) nums[i] = 1;
for(int i = 0; i < n; ++i){
int x = abs(nums[i]);
if(nums[x-1] > 0) nums[x-1] *= -1;
}
for(int i = 0; i < n; ++i)
if(nums[i] > 0) return i+1;
return n+1;
}
};
Java:
-----
class Solution {
public int firstMissingPositive(int[] nums) {
boolean contains_one = false;
for(int x: nums){
if(x == 1){
contains_one = true;
break;
}
}
if(!contains_one) return 1;
int n = nums.length;
if(n == 1) return 2;
for(int i = 0; i < n; ++i)
if(nums[i] <= 0 || nums[i] > n) nums[i] = 1;
for(int i = 0; i < n; ++i){
int x = Math.abs(nums[i]);
if(nums[x-1] > 0) nums[x-1] *= -1;
}
for(int i = 0; i < n; ++i)
if(nums[i] > 0) return i+1;
return n+1;
}
}
Python3:
-------
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
contains_one = False
for x in nums:
if x == 1:
contains_one = True
break
if not contains_one: return 1
n = len(nums)
if n == 1: return 2
for i in range(n):
if nums[i] <= 0 or nums[i] > n: nums[i] = 1
for i in range(n):
x = abs(nums[i])
if nums[x-1] > 0: nums[x-1] *= -1
for i in range(n):
if nums[i] > 0: return i+1
return n+1