LeetCode 40 First Missing Positive
2014-06-18 14:21
141 查看
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.
先排序,再检查,交换
或者,先交换排序,后检查
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) { sort(A, A+n); int res = 0; int i = 0; while (i<n && A[i]<=0) i++; for (; i < n; i++) {//注意:一看到序列就应该马上反应问题:是否有重复元素??? if (i>0 && A[i] == A[i-1]) continue; if (A[i] - res != 1) return res+1; else res = A[i]; } return res+1; } };
或者,先交换排序,后检查
class Solution { public: int firstMissingPositive(int A[], int n) { int i = 0; while (i < n) { if (A[i] != (i+1) && A[i] >= 1 && A[i] <= n && A[A[i]-1] != A[i]) swap(A[i], A[A[i]-1]); else i++; } for (i = 0; i < n; ++i) if (A[i] != (i+1)) return i+1; return n+1; } };
相关文章推荐
- LeetCode | First Missing Positive
- Leetcode First Missing Positive
- LEETCODE: First Missing Positive
- leetcode:First Missing Positive 菜鸟解法
- leetcode first missing positive,覆盖区间
- LeetCode-41-First Missing Positive 递归水题
- LeetCode--First Missing Positive
- Leetcode First Missing Positive 三个思路
- [LeetCode] First Missing Positive
- [LeetCode 141] First Missing Positive
- [LeetCode]First Missing Positive
- 【LeetCode 41】 First Missing Positive
- [Leetcode] First Missing Positive (Java)
- leetcode First Missing Positive
- leetcode 41 First Missing Positive
- leetcode第一刷_ First Missing Positive
- LeetCode "First Missing Positive"
- leetcode hard模式专杀之41 First Missing Positive
- leetcode-First Missing Positive
- [LeetCode] [First Missing Positive 2012-03-08]