您的位置:首页 > 其它

Leetcode-First Missing Positive

2014-11-26 23:14 357 查看
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.

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: