LeetCode: First Missing Positive
2015-01-15 15:27
204 查看
Given an unsorted integer array, find the first missing positive integer.
For example,
Given
and
Your algorithm should run in O(n) time and uses constant space.
Round 2;
class Solution {
public:
int firstMissingPositive(int A[], int n) {
if(n == 0)
return 1;
for(int i = 0; i < n; i++)
{
if(A[i] <= 0 || A[i] > n || A[i] == i+1 || A[A[i]-1] == A[i])
continue;
else
{
int temp = A[A[i]-1];
A[A[i]-1] = A[i];
A[i] = temp;
i--;
}
}
for(int i = 0; i < n; i++)
{
if(A[i] != i+1)
return i+1;
}
return n+1;
}
};
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.
class Solution { public: int firstMissingPositive(int A[], int n) { for(int i = 0; i < n; i++) { if(A[i] == i+1 || A[i] > n || A[i] <= 0 || A[A[i]-1] == A[i]) continue; int temp = A[A[i]-1]; A[A[i]-1] = A[i]; A[i] = temp; i--; } for(int i = 0; i < n; i++) { if(A[i] != i+1) return i+1; } return n+1; } };
Round 2;
class Solution {
public:
int firstMissingPositive(int A[], int n) {
if(n == 0)
return 1;
for(int i = 0; i < n; i++)
{
if(A[i] <= 0 || A[i] > n || A[i] == i+1 || A[A[i]-1] == A[i])
continue;
else
{
int temp = A[A[i]-1];
A[A[i]-1] = A[i];
A[i] = temp;
i--;
}
}
for(int i = 0; i < n; i++)
{
if(A[i] != i+1)
return i+1;
}
return n+1;
}
};
相关文章推荐
- First Missing Positive - Java Leetcode
- leetcode-First Missing Positive
- LeetCode-First Missing Positive
- Leetcode First Missing Positive
- LeetCode First Missing Positive
- [LeetCode] [First Missing Positive 2012-03-08]
- LeetCode_First Missing Positive
- [LeetCode][Java] First Missing Positive
- LeetCode 笔记系列11 First Missing Positive [为什么我们需要insight]
- leetcode First Missing Positive
- LeetCode-41-First Missing Positive 递归水题
- LeetCode 之 First Missing Positive
- leetcode: First Missing Positive
- LeetCode 41:First Missing Positive Number
- [LeetCode] First Missing Positive
- 【Leetcode】【python】First Missing Positive
- leetcode第一刷_ First Missing Positive
- 【leetcode】First Missing Positive
- LeetCode | First Missing Positive
- LeetCode----First Missing Positive