File tree 1 file changed +42
-0
lines changed
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ fn main ( ) {
2
+ Solution :: find_kth_largest ( vec ! [ 1 ] , 1 ) ;
3
+ }
4
+
5
+ struct Solution ;
6
+
7
+ impl Solution {
8
+ pub fn find_kth_largest ( nums : Vec < i32 > , k : i32 ) -> i32 {
9
+ let mut nums = nums;
10
+ Self :: heapify ( & mut nums) ;
11
+
12
+ for i in 1 ..k as usize {
13
+ Self :: heapify ( & mut nums[ i..] )
14
+ }
15
+
16
+ nums[ k as usize - 1 ]
17
+ }
18
+
19
+ fn heapify ( nums : & mut [ i32 ] ) {
20
+ let mut index = ( nums. len ( ) - 1 ) / 2 ;
21
+
22
+ for i in ( 0 ..=index) . rev ( ) {
23
+ Self :: down_heap ( nums, i) ;
24
+ }
25
+ }
26
+
27
+ fn down_heap ( nums : & mut [ i32 ] , mut index : usize ) {
28
+ while index * 2 + 1 < nums. len ( ) {
29
+ let mut max = index * 2 + 1 ;
30
+ if index * 2 + 2 < nums. len ( ) && nums[ index * 2 + 1 ] < nums[ index * 2 + 2 ] {
31
+ max = index * 2 + 2 ;
32
+ }
33
+
34
+ if nums[ max] > nums[ index] {
35
+ nums. swap ( max, index) ;
36
+ index = max;
37
+ } else {
38
+ break ;
39
+ }
40
+ }
41
+ }
42
+ }
You can’t perform that action at this time.
0 commit comments