-
-
Notifications
You must be signed in to change notification settings - Fork 611
/
KthLargestElementinanArray.java
46 lines (40 loc) · 1.24 KB
/
KthLargestElementinanArray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package problems.medium;
/**
* Created by sherxon on 2016-12-26.
*/
public class KthLargestElementinanArray {
/**
* This is quick select algorithm and average time complexity is O(N).
* We use k as a pivot.
* */
public int findKthLargest(int[] nums, int k) {
return partition(nums, 0, nums.length - 1, nums.length - k);
}
/*
* This is main point. This method rearranges the array in a way that all elements less than pivot
* are on left side of pivot and others on right. It then returns index of the pivot element.
* */
int partition(int[] a, int lo, int hi, int k) {
int p = lo + (hi - lo) / 2;
int storeIndex = lo;
swap(a, p, hi);
for (int i = lo; i < hi; i++) {
if (a[i] < a[hi]) {
swap(a, i, storeIndex);
storeIndex++;
}
}
swap(a, storeIndex, hi);
if (storeIndex == k)
return a[storeIndex];
else if (k < storeIndex)
return partition(a, lo, storeIndex - 1, k);
else
return partition(a, storeIndex + 1, hi, k);
}
private void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}