31、利用快速排序,寻找数组中第k大的数

一、题目

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

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

二、实现

注意:寻找第k大的数,需使用快速排序对数组进行递减排序

import java.util.*;

public class Solution {
    public int findKth(int[] a, int n, int K) {
        return findK(a,0,n-1,K);
    }
    // 1.快速排序,返回已排序元素下标
    public static int Quick(int[] a, int l, int h){
        int p = a[l];
        while(l<h){
            while(l<h && a[h]<=p) h--;
            if(l<h) a[l] = a[h];
            while(l<h && a[l]>=p) l++;
            if(l<h) a[h] = a[l];
        }
        a[l] = p;
        return l; //返回当前已排序的元素位置
    }
    // 2.查找第k大元素
    public static int findK(int[] a, int l, int h, int K){
        if(l <= h){
            int pos = Quick(a,l,h);
            if(pos == K-1){
                return a[pos];
            }
            else if(pos < K-1){ //右侧
                return findK(a,pos+1,h,K);
            }
            else{//左侧
                return findK(a,l,pos-1,K);
            }
       }
        return -1; //查找失败
     }
    
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值