First Missing Positive
2014-12-05 14:31
155 查看
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)的限制 。那么 其实 就是洗牌。。。。因为 数组是连续 的 那么肯定是 0 存1, 1的位置 存2 。。。。 i+1=A[i]。那么就按照 这个洗牌,当 A[A[i]-1]!=A[i], 那么 就 换下位置,然后 遍历一下 找不符合条件的就是第一个
class Solution {
public:
int firstMissingPositive(int A[], int n) {
for (int i=0; i<n; i++){
int digit=A[i];
while(digit>0 && digit <=n && A[digit-1]!=digit){
swap(A[digit-1],A[i]);
digit=A[i];
}
}
for (int i=0; i<n; i++){
if (i+1!=A[i])
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.
基本上暴力 排序是不行,因为 O(N)的限制 。那么 其实 就是洗牌。。。。因为 数组是连续 的 那么肯定是 0 存1, 1的位置 存2 。。。。 i+1=A[i]。那么就按照 这个洗牌,当 A[A[i]-1]!=A[i], 那么 就 换下位置,然后 遍历一下 找不符合条件的就是第一个
class Solution {
public:
int firstMissingPositive(int A[], int n) {
for (int i=0; i<n; i++){
int digit=A[i];
while(digit>0 && digit <=n && A[digit-1]!=digit){
swap(A[digit-1],A[i]);
digit=A[i];
}
}
for (int i=0; i<n; i++){
if (i+1!=A[i])
return i+1;
}
return n+1;
}
};
相关文章推荐
- First Missing Positive
- FTPrep, 41 First Missing Positive
- Leetcode#41||First Missing Positive
- leetCode (41)--First Missing Positive
- [LeetCode 141] First Missing Positive
- First Missing Positive
- LeetCode First Missing Positive
- Lintcode189 First Missing Positive solution 题解
- First Missing Positive
- LeetCode_First Missing Positive
- First Missing Positive
- First Missing Positive
- leetcode:First Missing Positive 【Java】
- leetcode--First Missing Positive
- LeetCode | First Missing Positive
- [LeetCode] First Missing Positive
- leetcode_c++:First Missing Positive(041)
- Leetcode: First Missing Positive
- First Missing Positive
- First Missing Positive