-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path41.first-missing-positive.cpp
73 lines (73 loc) · 1.41 KB
/
41.first-missing-positive.cpp
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
/*
* @lc app=leetcode id=41 lang=cpp
*
* [41] First Missing Positive
*
* https://leetcode.com/problems/first-missing-positive/description/
*
* algorithms
* Hard (27.51%)
* Total Accepted: 175K
* Total Submissions: 635.3K
* Testcase Example: '[1,2,0]'
*
* Given an unsorted integer array, find the smallest missing positive
* integer.
*
* Example 1:
*
*
* Input: [1,2,0]
* Output: 3
*
*
* Example 2:
*
*
* Input: [3,4,-1,1]
* Output: 2
*
*
* Example 3:
*
*
* Input: [7,8,9,11,12]
* Output: 1
*
*
* Note:
*
* Your algorithm should run in O(n) time and uses constant extra space.
*
*/
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int i=0;
int N=(int)nums.size();
int j = N-1;
while(i<=j){
if(nums[i]>0) i++;
else if(nums[j]<=0) j--;
else{
swap(nums[i], nums[j]);
i++;
j--;
}
}
// for(int p=0;p<N;p++) cout<<nums[p]<<" ";
cout<<"i:"<<i<<endl;
// if(nums[i]<=0)
// i--;
for(int j=0;j<i;j++){
int pos = abs(nums[j]);
if(pos > N) continue;
nums[pos-1] = -abs(nums[pos-1]);
}
// for(auto e:nums) cout<<e<<" ";
for(j=0;j<i;j++)
if(nums[j] < 0) continue;
else break;
return j+1;
}
};