标签:leetcode
https://oj.leetcode.com/problems/first-missing-positive/
http://blog.csdn.net/linhuanmars/article/details/20884585
public class Solution {
public int firstMissingPositive(int[] A) {
// 如果可以排序,排序后从1开始检查
// 如果一个数为3,把它置换到第三个空格
// i不动,继续置换,死循环!
// 如果i位 的值 < 0,i++
if (A == null || A.length == 0)
return 1;
int i = 0;
while (i < A.length)
{
if (A[i] <= 0 || A[i] > A.length)
{
// Invalid number we don‘t care
A[i] = -1;
i++;
continue;
}
if (A[i] == i + 1)
{
// Aready good
i ++;
continue;
}
// No need to swap
// Avoid dead loop
// 定义j方便coding
int j = A[i] - 1;
if (A[j] == A[i])
{
A[i] = -1;
i ++;
continue;
}
// swap A[i] and A[A[i] - 1]
int t = A[i];
A[i] = A[j];
A[j] = t;
}
// Check first -1
for (i = 0 ; i < A.length ; i ++)
{
if (A[i] < 0)
return i + 1;
}
return A.length + 1;
}
}[LeetCode]41 First Missing Positive
标签:leetcode
原文地址:http://7371901.blog.51cto.com/7361901/1598593