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.

Solution:

public class Solution {
    public int findKthLargest(int[] nums, int k) {
        int lo=0, hi=nums.length-1;
        int pos = -1;
        while(lo<=hi){
            pos = partition(nums, lo, hi);
            if(pos<nums.length-k){
                lo = pos + 1;
            } else if(pos>nums.length-k){
                hi = pos - 1;
            } else {
                break;
            }
        }
        return nums[pos];
    }
    public int partition(int[] nums, int low, int high){
        if(low==high) return low;
        int pivot=nums[low];
        int lo=low+1, hi=high;
        while(lo<=hi){
            while(lo<=hi && nums[lo]<=pivot) lo++;
            while(lo<=hi && nums[hi]>pivot) hi--;
            if(lo<hi) swap(nums, lo, hi);
        }
        swap(nums, low, hi);
        return hi;
    }
    public void swap(int[] nums, int i, int j){
        int tmp = nums[j];
        nums[j] = nums[i];
        nums[i] = tmp;
    }
}
comments powered by Disqus