题目描述
给出一个无序的整数型数组,求不在给定数组里的最小的正整数
例如:
给出的数组为[1,2,0] 返回3,
给出的数组为[3,4,-1,1] 返回2.
你需要给出时间复杂度在O(n)之内并且空间复杂度为常数级的算法
先利用快排 但有个问题 快排的时间复杂度O(nlogn)~O(n方)
最差情况:当数组原本就按从小到大顺序排列时:
10 20 30 40 50 60 70 80 第一轮比较,将10分别与20、30、...、80比较,共比较n-1次
第二轮比较,将20分别与30、...、80比较,共比较n-2次
....
共比较(n-1)+(n-2)+...+1次,即时间复杂度为O(n方),与冒泡排序时间复杂度一样
一般情况:时间复杂度为O(nlogn) 需要复杂的数学证明
import java.util.*;
public class Solution {
/**
*
* @param A int整型一维数组
* @return int整型
*/
public int firstMissingPositive (int[] A) {
if(A.length == 0){
return 1;
}
int len = A.length-1;
quickSort(A,0,len);
int temp = 1;
for(int i=0;i<A.length;i++){
if(A[i] >= 0 && temp >= A[i]){
temp = A[i] + 1;
}
}
return temp;
}
public void quickSort(int[] a,int low,int high){
if(low > high){
return;
}
int start = low;
int end = high;
int target = a[low];
while(start < end){
while(start < end && a[end] >= target){
end--;
}
while(start < end && a[start] <= target){
start++;
}
if(start < end){
int temp = a[end];
a[end] = a[start];
a[start] = temp;
}
}
if(start == end){
a[low] = a[end];
a[end] = target;
quickSort(a,low,end-1);
quickSort(a,end+1,high);
}
}
}