LeetCode--first-missing-positive
2018-01-16 13:36
453 查看
题目描述
Given an unsorted integer array, find the first missing positive integer.For example,
Given[1,2,0]return3,
and[3,4,-1,1]return2.
Your algorithm should run in O(n) time and uses constant space.
分析:利用数组的index来作为数字本身的索引,把正数按照递增顺序依次放到数组中。即让A[0]=1, A[1]=2, A[2]=3, ... , 这样一来,最后如果哪个数组元素违反了A[i]=i+1即说明i+1就是我们要求的第一个缺失的正数。对于那些不在范围内的数字,我们可以直接跳过,比如说负数,0,或者超过数组长度的正数,这些都不会是我们的答案。
与剑指offer中的数组中重复的数类似
class Solution { public: int firstMissingPositive(int A[], int n) { for(int i = 0; i < n; ++ i) while(A[i] > 0 && A[i] <= n && A[A[i] - 1] != A[i]) swap(A[i], A[A[i] - 1]); for(int 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 041 First Missing Positive
- LeetCode 41 First Missing Positive (思维)
- LeetCode——No.41 First Missing Positive
- First Missing Positive leetcode java
- leetcode:First Missing Positive 【Java】
- [LeetCode 141] First Missing Positive
- [LeetCode] First Missing Positive
- LeetCode:Missing Number And First Missing Positive
- [leetcode刷题系列]First Missing Positive
- LeetCode: First Missing Positive
- LeetCode 40 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——41——First Missing Positive