Skip to content

Commit bc77c9c

Browse files
Added Kth Largest Element in an Array
1 parent 19b5721 commit bc77c9c

File tree

3 files changed

+69
-4
lines changed

3 files changed

+69
-4
lines changed

LeetcodeProblems/Implement_stack_using_queues.js

+1-3
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,6 @@ Depending on your language, queue may not be supported natively. You may simulat
2424
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
2525
*/
2626

27-
28-
2927
class MyStack {
3028
constructor() {
3129
this.q1 = [];
@@ -95,4 +93,4 @@ var myStack = new MyStack();
9593
console.log(myStack.pop());
9694
}
9795

98-
module.exports.main = main;
96+
module.exports.main = main;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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;

LeetcodeProblems/Sum_Of_Square_Numbers.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ Input: 3
1414
Output: False
1515
*/
1616

17-
1817
/**
1918
* @param {number} c
2019
* @return {boolean}
@@ -42,3 +41,5 @@ var main = function() {
4241
console.log(judgeSquareSum(24));
4342
console.log(judgeSquareSum(25));
4443
}
44+
45+
module.exports.main = main;

0 commit comments

Comments
 (0)