-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path41.FirstMissingPositive.h
More file actions
72 lines (54 loc) · 1.67 KB
/
41.FirstMissingPositive.h
File metadata and controls
72 lines (54 loc) · 1.67 KB
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
/*
bluepp
2014-06-08
2014-07-10
2014-08-13
2014-10-22
2014-11-17
May the force be with you!
Problem: First Missing Positive
Source: https://oj.leetcode.com/problems/first-missing-positive/
Notes:
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
Solution: Although we can only use constant space, we can still exchange elements within input A!
Swap elements in A and try to make all the elements in A satisfy: A[i] == i + 1.
Pick out the first one that does not satisfy A[i] == i + 1.
*/
int firstMissingPositive(vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
while (nums[i] > 0 && nums[i] < n && nums[i] != nums[nums[i]-1]) {
swap(nums[i], nums[nums[i]-1]);
}
}
for (int i = 0; i < n; i++) {
if (nums[i] != i+1) {
return i+1;
}
}
return n+1;
}
/* 2016-06-17, update */
int firstMissingPositive(vector<int>& nums) {
int n = nums.size();
for(int i=0; i < n; i++)
{
while(nums[i]>= 1 && nums[i]<= n && nums[i]!=nums[nums[i]-1])
{
swap(nums[i], nums[nums[i]-1]);
}
}
int j=1;
for(; j <= n; j++)
{
if (nums[j-1] != j)
{
break;
}
}
return j;
}