leetcode First Missing Positive
2014-06-26 22:11
381 查看
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.
看到这道题目,需要时间为O(N)并且常数空间,所以需要在原来的数组中做工作。第一个miss的正整数,因为正整数是按照下标的顺序排列的,所以可以利用这点进行交换,
class Solution {
public:
int firstMissingPositive(int A[], int n) {
for(int i=0;i<n;){
if(A[i]>0&&A[i]!=(i+1)&&A[i]<n&&A[i]!=A[A[i]-1]){ //首先确保swap的地方没有越界,之后确保swap双方不一样,否则死循环。A[i]也没没有在最终位置
swap(A[i],A[A[i]-1]);
}
else{
i++;
}
}
for(int i=0;i<n;i++){
if(A[i]!=i+1)
return i+1;
}
return n+1;
}
void swap(int &a,int &b){
int temp=a;
a=b;
b=temp;
}
};
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.
看到这道题目,需要时间为O(N)并且常数空间,所以需要在原来的数组中做工作。第一个miss的正整数,因为正整数是按照下标的顺序排列的,所以可以利用这点进行交换,
class Solution {
public:
int firstMissingPositive(int A[], int n) {
for(int i=0;i<n;){
if(A[i]>0&&A[i]!=(i+1)&&A[i]<n&&A[i]!=A[A[i]-1]){ //首先确保swap的地方没有越界,之后确保swap双方不一样,否则死循环。A[i]也没没有在最终位置
swap(A[i],A[A[i]-1]);
}
else{
i++;
}
}
for(int i=0;i<n;i++){
if(A[i]!=i+1)
return i+1;
}
return n+1;
}
void swap(int &a,int &b){
int temp=a;
a=b;
b=temp;
}
};
相关文章推荐
- [LeetCode(Q41)] First Missing Positive (乱序数组中寻找第一个未出现的正整数)
- [Leetcode] First Missing Positive
- Java for LeetCode 041 First Missing Positive
- LeetCode First Missing Positive
- LeetCode First Missing Positive
- leetcode: First Missing Positive
- [LeetCode 题解]: First Missing Positive
- LeetCode:Missing Number And First Missing Positive
- [leetcode] First Missing Positive
- 81_leetcode_First Missing Positive
- leetcode——First Missing Positive
- LeetCode_FirstMissingPositive
- *LeetCode-First Missing Positive
- LeetCode -- First Missing Positive
- LeetCode--First Missing Positive
- Leetcode 41 - First Missing Positive
- leetcode-First Missing Positive
- 20170611-leetcode-041-First Missing Positive
- leetcode习题解答:First Missing Positive
- [leetcode]First Missing Positive