Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f9f2cfc

Browse files
committed
update: added K largest array elements
1 parent 042670a commit f9f2cfc

File tree

1 file changed

+22
-0
lines changed
  • src/_Problems_/k-largest-in-array

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const MaxHeap = require('../../_DataStructures_/Heaps/MaxHeap');
2+
3+
/**
4+
* Find the 4 largest elements from an array
5+
*/
6+
7+
function findKLargest(collection, k) {
8+
if (!collection || !Array.isArray(collection)) {
9+
throw new Error('Invalid / missing collection');
10+
}
11+
12+
// create a MaxHeap using the collection
13+
const mh = new MaxHeap(collection);
14+
const result = [];
15+
16+
for (let i = 0; i < k; i += 1) {
17+
result.push(mh.getMax());
18+
}
19+
return result;
20+
}
21+
22+
module.exports = findKLargest;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /