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.
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
You may assume k is always valid, 1 ≤ k ≤ array's length.
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findKthLargest = function (nums, k) {
let start = 0;
let end = k - 1;
debugger;
return quickSort(nums, 0, nums.length - 1, nums.length - k);
};
function swap(items, firstIndex, secondIndex) {
const temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
}
var partition = function (nums, start, end) {
let pivot = nums[Math.floor((start + end) / 2)];
let i = start;
let j = end;
while (i <= j) {
while (nums[i] < pivot) {
++i;
}
while (nums[j] > pivot) {
--j;
}
if (i <= j) {
swap(nums, i, j);
++i;
--j;
}
}
return i;
};
var quickSort = function (nums, start, end, findIndex) {
if (nums.length > 1) {
let index = partition(nums, start, end);
if (findIndex >= start && findIndex <= index - 1) {
if (start < index - 1) {
quickSort(nums, start, index - 1, findIndex);
}
} else {
if (index < end) {
quickSort(nums, index, end, findIndex);
}
}
}
console.log(nums);
return nums[findIndex]
};
findKthLargest([3, 2, 1, 5, 6, 4], 2);