Skip to content

Commit 5967643

Browse files
committed
feat: add ts solution to lc problem: No.0215
1 parent c74d816 commit 5967643

File tree

3 files changed

+83
-0
lines changed

3 files changed

+83
-0
lines changed

solution/0200-0299/0215.Kth Largest Element in an Array/README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,4 +335,36 @@ function findKthLargest(nums: number[], k: number): number {
335335

336336
<!-- solution:end -->
337337

338+
<!-- solution:start -->
339+
340+
### Solution 4: Hash + counting
341+
342+
<!-- tabs:start -->
343+
344+
#### TypeScript
345+
346+
```ts
347+
function findKthLargest(nums: number[], k: number): number {
348+
const n = 10 ** 4;
349+
const length = n * 2 + 1;
350+
const cnt = Array(length);
351+
352+
for (const x of nums) {
353+
cnt[x + n] = (cnt[x + n] ?? 0) + 1;
354+
}
355+
356+
for (let i = length; i >= 0; i--) {
357+
if (!cnt[i]) continue;
358+
k -= cnt[i];
359+
if (k <= 0) return i - n;
360+
}
361+
362+
return -1;
363+
}
364+
```
365+
366+
<!-- tabs:end -->
367+
368+
<!-- solution:end -->
369+
338370
<!-- problem:end -->

solution/0200-0299/0215.Kth Largest Element in an Array/README_EN.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,4 +327,38 @@ function findKthLargest(nums: number[], k: number): number {
327327

328328
<!-- solution:end -->
329329

330+
<!-- solution:end -->
331+
332+
<!-- solution:start -->
333+
334+
### Solution 4: Hash + counting
335+
336+
<!-- tabs:start -->
337+
338+
#### TypeScript
339+
340+
```ts
341+
function findKthLargest(nums: number[], k: number): number {
342+
const n = 10 ** 4;
343+
const length = n * 2 + 1;
344+
const cnt = Array(length);
345+
346+
for (const x of nums) {
347+
cnt[x + n] = (cnt[x + n] ?? 0) + 1;
348+
}
349+
350+
for (let i = length; i >= 0; i--) {
351+
if (!cnt[i]) continue;
352+
k -= cnt[i];
353+
if (k <= 0) return i - n;
354+
}
355+
356+
return -1;
357+
}
358+
```
359+
360+
<!-- tabs:end -->
361+
362+
<!-- solution:end -->
363+
330364
<!-- problem:end -->
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
function findKthLargest(nums: number[], k: number): number {
2+
const n = 10 ** 4;
3+
const length = n * 2 + 1;
4+
const cnt = Array(length);
5+
6+
for (const x of nums) {
7+
cnt[x + n] = (cnt[x + n] ?? 0) + 1;
8+
}
9+
10+
for (let i = length; i >= 0; i--) {
11+
if (!cnt[i]) continue;
12+
k -= cnt[i];
13+
if (k <= 0) return i - n;
14+
}
15+
16+
return -1;
17+
}

0 commit comments

Comments
 (0)