Leetcode-First Missing Positive
2014-11-26 23:14
357 查看
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.
Analysis:
The idea is to use the array itself as a table. We try put a value i on the place i-1. If the value i is out of range, i.e., <=0 || >n, then ignore it. At each position i, we check whether the A[i] is a value needed to be placed on its own position, if yes, we swap it; then we check the new A[i] again. We repeat this procedure until A[i] is a value that is out of range or the right place of value A[i] is already placed a value of A[i] (Duplicate situation), we then move the i+1 position.
Solution:
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.
Analysis:
The idea is to use the array itself as a table. We try put a value i on the place i-1. If the value i is out of range, i.e., <=0 || >n, then ignore it. At each position i, we check whether the A[i] is a value needed to be placed on its own position, if yes, we swap it; then we check the new A[i] again. We repeat this procedure until A[i] is a value that is out of range or the right place of value A[i] is already placed a value of A[i] (Duplicate situation), we then move the i+1 position.
Solution:
public class Solution { public int firstMissingPositive(int[] A) { int len = A.length; if (len==0) return 1; for (int i=0;i<len;i++) if (A[i]!=i+1){ int val = A[i]; while (true){ if (val<=0 || val>len) break; if (A[val-1]==val) break; swap(A,val-1,i); val = A[i]; } } int res = len+1; for (int i=0;i<len;i++) if (A[i]!=i+1){ res = i+1; break; } return res; } public void swap(int[] A, int i, int j){ int temp = A[i]; A[i]=A[j]; A[j] = temp; } }
相关文章推荐
- leetcode — first-missing-positive
- LeetCode力扣之First Missing Positive
- leetcode---first-missing-positive---数组
- [LeetCode][JavaScript]First Missing Positive
- leetcode-First Missing Positive
- LeetCode——No.41 First Missing Positive
- leetcode:First Missing Positive 【Java】
- LeetCode First Missing Positive
- First Missing Positive 找第一个没在array中出现的正数@LeetCode
- [LeetCode] First Missing Positive
- [Leetcode] 41 - First Missing Positive
- LeetCode题解——First Missing Positive
- LeetCode Online Judge 题目C# 练习 - First Missing Positive
- leetCode (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