First missing positive
2013-05-07 01:09
183 查看
题目:
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.
思路: 主要的思想就是把对应的数放到对应的索引上,例如1放到A[1]上,这样只需要O(n)的遍历就能完成,然后用一个O(n)的遍历找第一个没有放到索引上的数返回。
代码:
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.
思路: 主要的思想就是把对应的数放到对应的索引上,例如1放到A[1]上,这样只需要O(n)的遍历就能完成,然后用一个O(n)的遍历找第一个没有放到索引上的数返回。
代码:
class Solution { public: int firstMissingPositive(int A[], int n) { for (int i=0; i<n; ++i) { if (A[i] > 0 && A[i] < n) { if (A[i]-1 != i && A[A[i]-1] != A[i]) { int temp = A[A[i]-1]; A[A[i]-1] = A[i]; A[i] = temp; --i; } } } for (int j=0; j<n; ++j) if (A[j]-1 != j) return j+1; return n+1; } };
相关文章推荐
- leetcode--First Missing Positive
- findFirstMissingPositive
- LeetCode: First Missing Positive
- 《leetCode》:First Missing Positive
- LeetCode题解——First Missing Positive
- LeetCode 43: First Missing Positive
- Leetcode 41 - First Missing Positive
- LeetCode 笔记系列11 First Missing Positive [为什么我们需要insight]
- [leetcode Q41] First Missing Positive
- LeetCode——No.41 First Missing Positive
- [Leetcode 96] 41 First Missing Positive
- Given an unsorted integer array, find the first missing positive integer.
- LeetCode-First Missing Positive
- First Missing Positive 找第一个没在array中出现的正数@LeetCode
- Leet Code 41 First Missing Positive - Java
- First Missing Positive
- First Missing Positive
- 想到这一点,只要10分钟不到 - First Missing Positive
- 【LeetCode练习题】First Missing Positive
- LeetCode First Missing Positive