*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.

Note: 
You may assume k is always valid, 1 ≤ k ≤ array's length.

 

解法:quick select

参考Algorithm课quick sort的笔记

 
public class Solution {
public int findKthLargest(int[] nums, int k) {
    if (k < 1 || nums == null) {
        return 0;
    }
 
    return getKth(nums.length - k +1, nums, 0, nums.length - 1);
}
 
public int getKth(int k, int[] nums, int start, int end) {
 
    int pivot = nums[end];
        int storeIndex = start;        
        for (int i = start; i < end; i++) {
            if (nums[i] < pivot) {
                swap(nums, storeIndex, i);
                storeIndex++; // 交换位置后,storeIndex 自增 1,代表下一个可能要交换的位置
            }
        }
        swap(nums, end, storeIndex); // 将基准元素放置到最后的正确位置上
    
 
    if (k == storeIndex + 1) {
        return pivot;
    } else if (k < storeIndex + 1) {
        return getKth(k, nums, start, storeIndex - 1);
    } else {
        return getKth(k, nums, storeIndex + 1, end);
    }
}
 
public void swap(int[] nums, int n1, int n2) {
    int tmp = nums[n1];
    nums[n1] = nums[n2];
    nums[n2] = tmp;
}
}

 

posted @ 2016-01-14 06:11  Hygeia  阅读(204)  评论(0编辑  收藏  举报