Java给出一个无序的整数型数组,求不在给定数组里的最小的正整数

题目描述

给出一个无序的整数型数组,求不在给定数组里的最小的正整数

例如:

给出的数组为[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);
        }
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值