首页 > 其他 > 详细

Kth Largest Element

时间:2017-06-02 09:35:03      阅读:221      评论:0      收藏:0      [点我收藏+]

Node:

Quick Select: Avg O(N)

Thought: put all the element less(more) than pivot to the first part, the rest to the second part. And Kth only falls to one of the two sections. Just using the same idea to process that part is enough.

 

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
        if (nums  == null || nums.length == 0) {
            return -1;
        }
        return quickSelect(nums, 0, nums.length - 1, k);
    }
    
    private int quickSelect(int[] nums, int start, int end, int k)  {
        if (start == end) {
            return nums[start];
        }
        
        int pivot = nums[start + (end - start) / 2];
        int left = start;
        int right = end;
        while (left <= right) {
            while (left <= right && nums[left] > pivot) {
                left++;
            }
            while (left <= right && nums[right] < pivot) {
                right--;
            }
            if (left <= right) {
                int tmp = nums[left];
                nums[left] = nums[right];
                nums[right] = tmp;
                left++;
                right--;
            }
        }
        
        if (start + k - 1 <= right) {
            return quickSelect(nums, start, right, k);
        }
        if (start + k - 1 >= left) {
            //This is the k -(left - start)th of the last part
            return quickSelect(nums, left, end, k - (left - start));
        }  
        
        return nums[right + 1];
    }
};

 

Kth Largest Element

原文:http://www.cnblogs.com/codingEskimo/p/6931564.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!