码迷,mamicode.com
首页 > 其他好文 > 详细

Kth Largest Element in an Array

时间:2015-05-27 08:35:51      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
}

 

Kth Largest Element in an Array

标签:

原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4532430.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!