【LeetCode】First Missing Positive
2014-06-11 11:05
405 查看
题目描述:
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.
首先想到的当然是排序。题目要求O(n)的时间复杂度,快排的复杂度为O(n*logn),不符合条件。因此考虑用别的什么方法实现排序。
观察下题目发现有两个特点:
1、所求值为正数,这意味着小于等于0的数我们可以忽略掉。
2、最极端的例子1,2,3,4,5……n-1中最大值也是小于n的,这意味着大于等于n的数也可以忽略掉。
由此我们只要对1~n-1之间的数进行排序就好了。要求用常数空间,跟Remove Duplicates from Sorted Array题目类似,用原数组来进行排序,只要将A[i]放置到A[i]-1的位置就好了,即满足上述两个条件时,swap(A[i], A[A[i] - 1])。为了避免无限循环和出现重复项,还需要加个判定条件A[A[i]
- 1] != A[i]。
代码如下:
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.
首先想到的当然是排序。题目要求O(n)的时间复杂度,快排的复杂度为O(n*logn),不符合条件。因此考虑用别的什么方法实现排序。
观察下题目发现有两个特点:
1、所求值为正数,这意味着小于等于0的数我们可以忽略掉。
2、最极端的例子1,2,3,4,5……n-1中最大值也是小于n的,这意味着大于等于n的数也可以忽略掉。
由此我们只要对1~n-1之间的数进行排序就好了。要求用常数空间,跟Remove Duplicates from Sorted Array题目类似,用原数组来进行排序,只要将A[i]放置到A[i]-1的位置就好了,即满足上述两个条件时,swap(A[i], A[A[i] - 1])。为了避免无限循环和出现重复项,还需要加个判定条件A[A[i]
- 1] != A[i]。
代码如下:
class Solution { public: int firstMissingPositive(int A[], int n) { for (int i = 0; i < n; i++){ if (A[i] <= 0 || A[A[i] - 1] == A[i]|| A[i] >= n) continue; swap(A[i], A[A[i] - 1]); i--; } int count(0); for (int i = 0; i < n; i++){ if (A[i] <= 0) continue; count++; if (count != A[i]) return count; } return ++count; } };
相关文章推荐
- LeetCode 41:First Missing Positive Number
- First Missing Positive - Java Leetcode
- LeetCode First Missing Positive
- Leetcode First Missing Positive
- First Missing Positive 找第一个没在array中出现的正数@LeetCode
- [LeetCode] First Missing Positive
- LeetCode Online Judge 题目C# 练习 - First Missing Positive
- First Missing Positive leetcode
- [leetcode]First Missing Positive
- leetcode First Missing Positive
- LeetCode-First Missing Positive
- [LeetCode][Java] First Missing Positive
- LeetCode-41-First Missing Positive 递归水题
- LeetCode First Missing Positive
- [LeetCode]First Missing Positive
- First Missing Positive(leetcode)
- leetcode--First Missing Positive
- leetcode First Missing Positive python
- [LeetCode] [First Missing Positive 2012-03-08]
- 【Leetcode】【python】First Missing Positive