Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

思路:

回顾quick sort

https://www.cse.ust.hk/~dekai/271/notes/L01a/quickSort.pdf

好看的video

https://www.youtube.com/watch?v=8hHWpuAPBHo

 

qs的改进

http://blog.csdn.net/linqiaqun/article/details/8832852

本题code ref

http://blog.csdn.net/u012925008/article/details/45965627

public class Solution {
    public int findKthLargest(int[] nums, int k) {
    //http://blog.csdn.net/u012925008/article/details/45965627
        return quickSt(nums, 0, nums.length-1,k-1);
    }
    public int quickSt(int[] n, int l, int h, int k){
        if(l<=h){
            int m = adj(n,l,h);
            if(m==k) return n[m];
            if(m<k) return quickSt(n,m+1,h,k);
            if(m>k) return quickSt(n,l,m-1,k);
        }
        return -1;
    }
    public int adj(int[] n, int l, int h){
        int t = n[l]; // pivot
        while(l<h){
            
            while(l<h && n[h]<=t) h--;
            n[l] = n[h];
            while(l<h && n[l]>=t) l++;
            n[h] = n[l];
        }
        n[l]=t;
        return l;
    }
}

 

posted @ 2015-05-27 08:27  世界到处都是小星星  阅读(162)  评论(0编辑  收藏  举报