[LeetCode] 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.

思路是使用桶排序的原理。


1)通过使用swap函数,调换所有元素使得A[i] = i + 1。

2)遍历调整后的数组,违背调整后规律的数就是missing value了。


两个数之间的调换发生时必须满足以下三种情况:

1) A[i] != i + 1;

2)A[i]的值必须在[1, n]范围内,n为数组长度;

3)两个被置换的值,即A[i]和A[A[i]-1],必须不相等。(否则会造成死循环)

	private void swap(int[] A, int i, int j) {
		int temp = A[i];
		A[i] = A[j];
		A[j] = temp;
	}

	public int firstMissingPositive(int[] A) {
		int i = 0;
		while (i < A.length) {
			if (A[i] != i + 1
					&& (A[i] > 0 && A[i] <= A.length && A[i] != A[A[i] - 1])) {
				swap(A, i, A[i] - 1);
			} else {
				i++;
			}
		}

		// scan again to identify the missing integer
		for (i = 0; i < A.length; i++) {
			if (A[i] != i + 1)
				return i + 1;
		}

		// e.g., if the input is {1, 2, 3}, then 4 is missing
		return A.length + 1;
	}


你可能感兴趣的:(LeetCode,first,Missing,Positi)