寻找第K大----快排的思路

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43573534/article/details/99714277
链接:https://www.nowcoder.com/questionTerminal/e016ad9b7f0b45048c58a9f27ba618bf
来源:牛客网

有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数。

给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在。

测试样例:
[1,3,5,2,2],5,3
返回:2

题解:K值的变更

import java.util.*;

public class Finder{
    public int findKth(int[] a ,int n, int K){
       return findKth(a,0,n-1,K);
    }
    public int findKth(int[] a ,int low,int high,int k){
//基准点的选取
        int p = partation(a,low,high);
//判断第K大的数值在左右哪个区间
        if(k == p-low+1){
            return a[p];
        }else if(k < p-low+1){
            return findKth(a,low,p-1,k);
        }else {
            return findKth(a,p+1,high,k-p+low-1);
        }
    }
    public int partation(int[] a ,int low,int high){
        int key = a[low];
        while (low < high){
            while (low < high && a[high] < key){
                high--;
            }
            while (low < high && a[low] > key){
                low++;
            }
            if(low < high){
                int temp = a[low];
                a[low] = a[high];
                a[high] = temp;
            }
        }
        a[low] = key;
        return low;
    }
}

有需要的朋友可以看一下我之前的关于快排的文章

猜你喜欢

转载自blog.csdn.net/weixin_43573534/article/details/99714277
今日推荐