-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path41.cpp
More file actions
34 lines (31 loc) · 829 Bytes
/
41.cpp
File metadata and controls
34 lines (31 loc) · 829 Bytes
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
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int n = nums.size();
bool oneFlag = false;
for (auto& num : nums) {
if (num == 1) {
oneFlag = true;
break;
}
}
if (!oneFlag) return 1;
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 index = abs(nums[i]);
if (index == n) {
nums[0] = -1 * abs(nums[0]);
}
else {
nums[index] = -1 * abs(nums[index]);
}
}
for (int i = 1; i < n; ++i) {
if (nums[i] > 0) return i;
}
if (nums[0] > 0) return n;
return n + 1;
}
};