Kth Largest Element

Find K-th largest element in an array.

Note

You can swap elements in the array

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.

Challenge

O(n) time, O(1) space

 

Kth Largest Element

public int kthLargestElement(int k, ArrayList<Integer> numbers) {
    int N = numbers.size();
    Integer[] A = new Integer[N];
    numbers.toArray(A);
    k = N - k; // 0 based kth smallest index
    return kthSmallest(A, 0, N-1, k);
}

public int kthSmallest(Integer[] A, int lo, int hi, int k) {
    if(k<lo || k>hi) return -1;
    int p = partition(A, lo, hi);
    if(p == k) return A[p];
    if(p < k) {
        return kthSmallest(A, p+1, hi, k);
    } else {
        return kthSmallest(A, lo, p-1, k);
    }
}

private int partition(Integer[] A, int lo, int hi) {
    int pivot = A[hi];
    int p = lo;
    for(int i=lo; i<hi; i++) {
        if(A[i] < pivot) {
            swap(A, i, p++);
        }
    }
    swap(A, p, hi);
    return p;
}

private void swap(Integer[] A, int i, int j) {
    Integer tmp = A[i];
    A[i] = A[j];
    A[j] = tmp;
}

 

References:

http://www.algorithmsandme.com/2013/08/find-kth-smallest-element-application.html

http://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array/

你可能感兴趣的:(element)