LeetCode 215.
Tags: LeetCode
class Solution {
public int findKthLargest(int[] nums, int k) {
int[] result = mergeSort(0, nums.length-1, nums);
return result[nums.length-k];
}
public int[] mergeSort(int start, int end, int[] arr) {
int half = (int)((end - start) * 0.5);
if (end - start < 2) {
return cmp(start, end, arr);
}
return conquer(mergeSort(start, start + half, arr),
mergeSort(start + half + 1, end, arr));
}
public int[] cmp(int start, int end, int[] arr) {
if (end - start == 0) return new int[]{arr[start]};
if (arr[end] < arr[start]) return new int[]{arr[end], arr[start]};
return new int[]{arr[start], arr[end]};
}
public int[] conquer(int[] a, int[] b){
int pta = 0, ptb = 0;
int[] result = new int[a.length + b.length];
while (pta < a.length && ptb < b.length) {
if (a[pta] <= b[ptb]) {
result[pta + ptb] = a[pta];
pta++;
}else{
result[pta + ptb] = b[ptb];
ptb++;
}
}
if (pta == a.length) {
for (int i=ptb; ptb<b.length; ptb++) {
result[a.length+ptb]=b[ptb];
}
}else{
for (int i=pta; pta<a.length; pta++) {
result[b.length+pta]=a[pta];
}
}
return result;
}
}