leetcode--First Missing Positive
2013-08-25 00:26
417 查看
1.题目描述
2.解法分析
解法:遍历数组,将遇到的正数放到对应的位置,也就是正数i应该放在A[i-1]处。
为什么呢?最直接的算法莫过于排序了,但是时间复杂度满足不了要求,然后就是hash了,但是普通的hash无法满足常数量级的额外空间要求,那么这个题目的思路就是用数组本身作为hash的空间,然后就有了这个解法。
[code]Given an unsorted integer array, find the first missing positive integer. 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. [/code] |
2.解法分析
解法:遍历数组,将遇到的正数放到对应的位置,也就是正数i应该放在A[i-1]处。
为什么呢?最直接的算法莫过于排序了,但是时间复杂度满足不了要求,然后就是hash了,但是普通的hash无法满足常数量级的额外空间要求,那么这个题目的思路就是用数组本身作为hash的空间,然后就有了这个解法。
class Solution { public: int firstMissingPositive(int A[], int n) { // Start typing your C/C++ solution below // DO NOT write int main() function if(n==0)return 1; int i=0; while(i<n) { if(A[i]>0&&A[i]<=n) { if(A[i]!=A[A[i]-1]) { int temp=A[i]; A[i]=A[A[i]-1]; A[temp-1]=temp; continue; } else i++; } else { A[i]=0;i++; } } i=0; while(i<n) { if(A[i]!=(i+1))return i+1; i++; } return n+1; } }; |
相关文章推荐
- leetcode之first missing positive
- LeetCode 041 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
- 【LeetCode】First Missing Positive
- LeetCode刷题笔录First Missing Positive
- [leetcode] #41 First Missing Positive
- leetcode--First Missing Positive
- LeetCode First Missing Positive
- 【Leetcode】【python】First Missing Positive
- leetcode question 41: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] 030: First Missing Positive