Kth Largest Element(第k大元素)

问题

Find K-th largest element in an array.

Notice

You can swap elements in the array

Have you met this question in a real interview? Yes
Example
In array [9,3,2,4,8], the 3rd largest element is 4.

In array [1,2,3,4,5], the 1st largest element is 5, 2nd largest element is 4, 3rd largest element is 3 and etc.

分析

使用快速排序,但是注意的是每次只需要根据对应的角标位置,递归排序一部分即可。

代码

class Solution {
    /*
     * @param k : description of k
     * @param nums : array of nums
     * @return: description of return
     */
    public int kthLargestElement(int k, int[] nums) {
        // write your code here
        return tree(nums.length-k,0,nums.length-1,nums);
    }
    private int tree(int k,int l,int r,int[] nums){
        int start=l;
        int end=r;
        int key=nums[l];
        while(l=key){
                r--;
            }
            nums[l]=nums[r];
            while(l

你可能感兴趣的:(Kth Largest Element(第k大元素))