题解 | #寻找第K大#

寻找第K大

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

import java.util.*;

public class Solution {
    public int findKth(int[] a, int n, int K) {
        // write code here
        return headSort(a, n, K);
    }    
    int headSort(int[] a, int n, int K){
        int i;
        int end = n - 1;
        int count = 0 ;
        for(i=(end-1)/2 ; i>=0 ; i--)//从第一个非叶子节点开始调整
            headAdjest(a, i, end);
        count++;
        for(i=end ; i>0 ; i--, count++){
           int temp = a[0];
            a[0] = a[i];
            a[i] = temp;
            if(K == count)//找到第K个大的数
                return a[i];
            headAdjest(a,0,i-1);
        }
        return a[n-K];
    }
    void headAdjest(int[] a, int start, int end){
        int temp = a[start];
        int j;
        
        for(j=start*2+1 ; j<=end ; j=j*2+1){
            if(j<end && a[j]<a[j+1])j++;//寻找孩子中更大的一个
            if(temp > a[j])break;//父》子 无需调整
            a[start] = a[j];
            start = j;
        }
        a[start] = temp;
    }
}
全部评论

相关推荐

迷茫的大四🐶:自信一点,我认为你可以拿到50k,低于50k完全配不上你的能力,兄弟,不要被他们骗了,你可以的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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