File tree Expand file tree Collapse file tree 2 files changed +77
-0
lines changed Expand file tree Collapse file tree 2 files changed +77
-0
lines changed Original file line number Diff line number Diff line change
1
+ [3,2,3,1,2,4,5,5,6]
2
+ 4
Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode.cn id=215 lang=javascript
3
+ *
4
+ * [215] 数组中的第K个最大元素
5
+ *
6
+ * 1. 使用容量为 k 的最小堆
7
+ * 2. 最终堆内就是最大的 k 个数字, 堆顶就是结果
8
+ */
9
+
10
+ // @lc code=start
11
+ /**
12
+ * @param {number[] } nums
13
+ * @param {number } k
14
+ * @return {number }
15
+ */
16
+ var findKthLargest = function ( nums , k ) {
17
+ const heap = [ ] ;
18
+
19
+ for ( const n of nums ) {
20
+ if ( heap . length === k ) {
21
+ if ( n < heap [ 0 ] ) {
22
+ continue ;
23
+ }
24
+
25
+ heap [ 0 ] = heap [ heap . length - 1 ] ;
26
+ heap . pop ( ) ;
27
+
28
+ let i = 0 ;
29
+ while ( i < heap . length ) {
30
+ let next = i ;
31
+
32
+ if ( heap [ i * 2 + 1 ] && heap [ i * 2 + 1 ] < heap [ next ] ) {
33
+ next = i * 2 + 1 ;
34
+ }
35
+ if ( heap [ i * 2 + 2 ] && heap [ i * 2 + 2 ] < heap [ next ] ) {
36
+ next = i * 2 + 2 ;
37
+ }
38
+
39
+ if ( i === next ) {
40
+ break ;
41
+ }
42
+
43
+ const t = heap [ i ] ;
44
+ heap [ i ] = heap [ next ] ;
45
+ heap [ next ] = t ;
46
+ i = next ;
47
+ }
48
+ }
49
+
50
+ heap [ heap . length ] = n ;
51
+
52
+ let i = heap . length - 1 ;
53
+ while ( i > 0 ) {
54
+ let next = Math . floor ( ( i - 1 ) / 2 ) ;
55
+ if ( heap [ next ] < heap [ i ] ) {
56
+ break ;
57
+ }
58
+
59
+ const t = heap [ i ] ;
60
+ heap [ i ] = heap [ next ] ;
61
+ heap [ next ] = t ;
62
+ i = next ;
63
+ }
64
+ }
65
+
66
+ return heap [ 0 ] ;
67
+ } ;
68
+
69
+ // var findKthLargest = function(nums, k) {
70
+ // nums.sort((a, b) => b - a);
71
+ // return nums[k - 1];
72
+ // };
73
+
74
+ // @lc code=end
75
+
You can’t perform that action at this time.
0 commit comments