题目:https://oj.leetcode.com/problems/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.
分析:本质上是桶排序(bucket sort),每当A[i]!= i+1 的时候,将A[i] 与A[A[i]-1] (下标值要减1)交换,直到无法交换为止,终止条件是A[i]== A[A[i]-1]。作用就是把A[i]放到小标为A[i]-1的位置,遇到负值或大于n的值则退出,最后扫描数组,若A[i]!=i+1,说明在A[i]处不连续。源码:Java版本
算法分析:时间复杂度O(n),空间复杂度O(1)
public class Solution {
public int firstMissingPositive(int[] A) {
bucketSort(A);
for(int i=0;i<A.length;i++) {
if(A[i]!=i+1) {
return i+1;
}
}
return A.length+1;
}
private void bucketSort(int[] A) {
for(int i=0;i<A.length;i++) {
while(A[i]!=i+1) {
if(A[i]<=0 || A[i]>A.length || A[i]==A[A[i]-1]) {
break;
}
swap(A,i,A[i]-1);
}
}
}
private void swap(int[] A,int x,int y) {
int temp=A[x];
A[x]=A[y];
A[y]=temp;
}
}
注:欢迎各位补充时间复杂度的分析过程。