LeetCode: First Missing Positive 解题报告

First Missing Positive

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.

SOLUTION 1:

使用类似桶排序的方法:

将值放在它应该在的位置,最后再扫描一次得出哪个位置有缺少值。

引自:

http://m.blog.csdn.net/blog/hellobinfeng/17348055

http://n00tc0d3r.blogspot.com/2013/03/find-first-missing-positive.html

http://www.cnblogs.com/AnnieKim/archive/2013/04/21/3034631.html

A few quick thoughts:

  • Sort all numbers and iterate through to find the first missing integer? No, most sorting algorithms take time at least O(nlogn).
  • How about linear sorting algorithm? No, bucket sort requires O(n) space.
  • Mapping all positive integers to a hash table and iterate from 1 to the length of the array to find out the first missing one? No, hash table requires O(n) space.

Then, how to solve this?

Let's take another look at the problem. It is asking for the first missing POSITIVE integer.
So, given a number in the array,

  • if it is non-positive, ignore it;
  • if it is positive, say we have A[i] = x, we know it should be in slot A[x-1]! That is to say, we can swap A[x-1] with A[i] so as to place x into the right place.
We need to keep swapping until all numbers are either non-positive or in the right places. The result array could be something like [1, 2, 3, 0, 5, 6, ...]. Then it's easy to tell that the first missing one is 4 by iterate through the array and compare each value with their index.

LeetCode: First Missing Positive  解题报告

解1:

 public int firstMissingPositive1(int[] A) {
// bug 3: when length is 0, return 1;
if (A == null) {
return 0;
} for (int i = 0; i < A.length; i++) {
// BUG 1: TLE , should judge when A[i] - 1 == i;
while (A[i] - 1 != i && A[i] > 0) {
// bug 2: cant exchange a same node: A[A[i] - 1] != A[i]
if (A[i] - 1 < A.length && A[A[i] - 1] != A[i]) {
swap(A, i, A[i] - 1);
} else {
// when the number is out of range, delete it.
A[i] = 0;
}
}
} for (int i = 0; i < A.length; i++) {
if (A[i] <= 0) {
return i + 1;
}
} return A.length + 1;
} public void swap(int[] A, int l, int r) {
int tmp = A[l];
A[l] = A[r];
A[r] = tmp;
}

简化后,解2:

其实交换的条件就是3个:

1: A[i] is in the range;
2: A[i] > 0.
3: The target is different; (如果不判断这个,会造成死循环,因为你交换过来一个一样的值)

 // SOLUTION 2:
public int firstMissingPositive(int[] A) {
// bug 3: when length is 0, return 1;
if (A == null) {
return 0;
} for (int i = 0; i < A.length; i++) {
// 1: A[i] is in the range;
// 2: A[i] > 0.
// 3: The target is different;
while (A[i] <= A.length && A[i] > 0 && A[A[i] - 1] != A[i]) {
swap(A, i, A[i] - 1);
}
} for (int i = 0; i < A.length; i++) {
if (A[i] != i + 1) {
return i + 1;
}
} return A.length + 1;
}

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/array/FirstMissingPositive.java

上一篇:细说tomcat之集群session共享方案


下一篇:深入浅出-网络七层模型&&网络数据包