题解 | #寻找第K大#

寻找第K大

http://www.nowcoder.com/practice/e016ad9b7f0b45048c58a9f27ba618bf

基于快排:每次划分之后返回该次划分的基准索引,比较索引和K的大小,K大,则往右继续划分,K小,则往右划分。直到求解为止。该算法不会把快排执行完毕,也就是说数组中还有没有排好序的一些元素。

public class Solution {
    public int findKth(int[] a, int n, int K) {
         quicksort(a,0,n-1,K);
        return a[K-1];
    }
    public void quicksort(int[] a, int low,int high , int K){
        if(low<high){
            int mid = partion(a,low,high);
            if(mid==K-1)return;
            else if(mid<K-1){
                 quicksort(a,mid+1,high,K);
            }
            else 
                quicksort(a,low,mid-1,K);
        }
    }
    public int partion(int [] a,int low,int high){
        int pivot = a[low];
        while(low<high){
            while(low<high&&a[high]<=pivot)--high;
            a[low] = a[high];
            while(low<high&&a[low]>=pivot)++low;
            a[high] = a[low];
            a[low] = pivot;
        }
        return low;
    }
}
全部评论

相关推荐

07-23 15:05
门头沟学院 Java
熊大不大:不好意思KPI数据刚刚刷新,刚刚达标
点赞 评论 收藏
分享
06-26 17:24
已编辑
宁波大学 golang
迷失西雅图:别给,纯kpi,别问我为什么知道
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务