Loading...

快排思想-寻找第K大

在这里插入图片描述

求解代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
private void swap(int[] arr,int i,int j){
        if(i!=j){
            arr[i]^=arr[j];
            arr[j]^=arr[i];
            arr[i]^=arr[j];
        }
    }
    public int findKth (int[] a, int n, int K) {
        K=n-K;

        int low = 0,high = n-1;

        while(low<=high){

            int i = low;

            for(int j=low+1;j<=high;j++){
                if(a[j]<a[low]){
                    swap(a,j,++i);
                }
            }
            swap(a, low, i);
            if(K==i){
                return a[i];
            }else if(K<i){
                high=i-1;
            }else{
                low=i+1;
            }        
        }
        return -1;

    }

小贴士

数组中第K大的数对应的就是数组下标为n-K的数

最后更新于 2026-04-05 17:35:33
Code Road Record