[LeetCode] First Missing Positive
2012-10-31 11:34
330 查看
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.
参考这里的解答:http://dl.dropbox.com/u/19732851/LeetCode/FirstMissingPositive.html
主要的思想就是把对应的数放到对应的索引上,例如1放到A[1]上,这样只需要O(n)的遍历就能完成,然后用一个O(n)的遍历找第一个没有放到索引上的数返回。
最后就是可能A[0] == n,这时就要有个特殊情况的处理。
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.
参考这里的解答:http://dl.dropbox.com/u/19732851/LeetCode/FirstMissingPositive.html
主要的思想就是把对应的数放到对应的索引上,例如1放到A[1]上,这样只需要O(n)的遍历就能完成,然后用一个O(n)的遍历找第一个没有放到索引上的数返回。
最后就是可能A[0] == n,这时就要有个特殊情况的处理。
class Solution { public: int firstMissingPositive(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int i = 0; while(i < n) { if (A[i] == i) i++; else { if (0 <= A[i] && A[i] < n && A[A[i]] != A[i]) { int t = A[i]; A[i] = A[A[i]]; A[t] = t; continue; } else i++; } } for(int i = 1; i < n; i++) if (A[i] != i) return i; return A[0] == n ? n + 1 : n; } };
相关文章推荐
- Leetcode:First Missing Positive
- LeetCode--First Missing Positive (第一个丢失的正整数)Python
- 【LeetCode】First Missing Positive
- Leetcode First Missing Positive
- First Missing Positive leetcode
- [leetcode]First Missing Positive
- [leetcode]First Missing Positive
- [LeetCode] First Missing Positive 解题报告
- First Missing Positive -- LeetCode
- LeetCode: First Missing Positive
- leetcode 41:First Missing Positive
- (LeetCode 41)First Missing Positive
- LeetCode First Missing Positive
- leetcode First Missing Positive
- leetcode: First Missing Positive
- 【leetcode】 First Missing Positive
- leetcode:First Missing Positive 【Java】
- [Leetcode 41] First Missing Positive
- leetcode || 41、First Missing Positive 问题
- Leetcode: First Missing Positive