|
| 1 | +/* |
| 2 | +Kth Largest Element in an Array |
| 3 | +https://leetcode.com/problems/kth-largest-element-in-an-array/description/ |
| 4 | +
|
| 5 | +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. |
| 6 | +
|
| 7 | +Example 1: |
| 8 | +
|
| 9 | +Input: [3,2,1,5,6,4] and k = 2 |
| 10 | +Output: 5 |
| 11 | +Example 2: |
| 12 | +
|
| 13 | +Input: [3,2,3,1,2,4,5,5,6] and k = 4 |
| 14 | +Output: 4 |
| 15 | +Note: |
| 16 | +You may assume k is always valid, 1 ≤ k ≤ array's length. |
| 17 | +*/ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number[]} nums |
| 21 | + * @param {number} k |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var findKthLargest = function(nums, k) { |
| 25 | + for(var i = Math.floor(nums.length/2) - 1; i >= 0; i--) { |
| 26 | + heapify(nums, nums.length, i); |
| 27 | + } |
| 28 | + |
| 29 | + for(var i = nums.length -1; i >= nums.length - k - 1 && i >= 0; i--) { |
| 30 | + swap(nums, 0, i); |
| 31 | + heapify(nums, i, 0); |
| 32 | + } |
| 33 | + |
| 34 | + return nums[nums.length - k]; |
| 35 | +} |
| 36 | + |
| 37 | +var heapify = function(nums, length, i) { |
| 38 | + var left = 2 * i + 1; |
| 39 | + var right = 2 * i + 2; |
| 40 | + |
| 41 | + if(left >= length) |
| 42 | + return; |
| 43 | + |
| 44 | + if(nums[i] < nums[left] && (right >= length || nums[left] > nums[right])) { |
| 45 | + swap(nums, left, i); |
| 46 | + heapify(nums, length, left); |
| 47 | + } else if(right < length && nums[right] > nums[i]) { |
| 48 | + swap(nums, right, i) |
| 49 | + heapify(nums, length, right) |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +var swap = function(nums, a, b) { |
| 54 | + const temp = nums[a]; |
| 55 | + nums[a] = nums[b]; |
| 56 | + nums[b] = temp; |
| 57 | +} |
| 58 | + |
| 59 | +var main = function(nums) { |
| 60 | + console.log(findKthLargest([3,2,1,5,6,4], 2)); |
| 61 | + console.log(findKthLargest([3,2,3,1,2,4,5,5,6], 4)); |
| 62 | + console.log(findKthLargest([0], 1)); |
| 63 | + console.log(findKthLargest([], 1)); |
| 64 | +} |
| 65 | + |
| 66 | +module.exports.main = main; |
0 commit comments