-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Sync LeetCode submission - Kth Largest Element in an Array (javascript)
- Loading branch information
1 parent
92d28f0
commit 720f831
Showing
1 changed file
with
23 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
/** | ||
* @param {number[]} nums | ||
* @param {number} k | ||
* @return {number} | ||
*/ | ||
var findKthLargest = function(nums, k) { | ||
// Create a new Min Priority Queue to store the k largest elements. | ||
let pq = new MinPriorityQueue(); | ||
|
||
// Iterate through each element 'x' in the 'nums' array. | ||
for (let x of nums) { | ||
// Enqueue the current element 'x' into the priority queue. | ||
pq.enqueue(x); | ||
|
||
// If the size of the priority queue becomes larger than 'k', remove the smallest element. | ||
if (pq.size() > k) { | ||
pq.dequeue(); | ||
} | ||
} | ||
|
||
// Return the element at the front of the priority queue, which is the kth largest element. | ||
return pq.front().element; | ||
}; |