lintcode-medium-Kth Largest Element

Find K-th largest element in an array.

 

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
        
        if(nums == null || nums.length == 0 || k < 0 || k > nums.length)
            return 0;
        
        return quickSelect(nums, 0, nums.length - 1, nums.length - k);
    }
    
    public int quickSelect(int[] nums, int start, int end, int k){
        
        int left = start;
        int right = end;
        int pivot = end;
        
        while(true){
            while(left < right && nums[left] < nums[pivot])
                left++;
            while(left < right && nums[right] >= nums[pivot])
                right--;
            
            if(left == right)
                break;
            
            swap(nums, left, right);
        }
        
        swap(nums, left, pivot);
        
        if(k == left)
            return nums[k];
        else if(k < left)
            return quickSelect(nums, start, left - 1, k);
        else
            return quickSelect(nums, left, end, k);
    }
    
    public void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
        
        return;
    }
    
};

 

posted @ 2016-03-24 13:11  哥布林工程师  阅读(167)  评论(0编辑  收藏  举报