File tree Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change @@ -153,3 +153,9 @@ so that you can use `just tf TEST` command to test.
153153| - | - | - |
154154| 200. Number of Islands | Medium | [ 200_number_of_islands.rs] ( ./tests/200_number_of_islands.rs ) |
155155| 695. Max Area of Island | Medium | [ 695_max_area_of_island.rs] ( ./tests/695_max_area_of_island.rs ) |
156+
157+ ### Heap / Priority Queue
158+
159+ | Problem | Difficulty | Solution |
160+ | - | - | - |
161+ | 703. Kth Largest Element in a Stream | Easy | [ 703_kth_largest_element_in_a_stream.rs] ( ./tests/703_kth_largest_element_in_a_stream.rs ) |
Original file line number Diff line number Diff line change 1+ // 703. Kth Largest Element in a Stream
2+ // https://leetcode.com/problems/kth-largest-element-in-a-stream/description/
3+ // Topics: Heap / Priority Queue.
4+ // Difficulty: Easy.
5+
6+ #![ allow( unused) ]
7+
8+ #[ test]
9+ fn test_703_kth_largest_element_in_a_stream ( ) { }
10+
11+ #[ derive( Debug ) ]
12+ pub struct Solution ;
13+
14+ // ---------------------------------
15+ // copy to leetcode starts from here
16+ // ---------------------------------
17+
18+ use std:: cmp:: Reverse ;
19+ use std:: collections:: BinaryHeap ;
20+
21+ struct KthLargest {
22+ k : usize ,
23+ nums : BinaryHeap < Reverse < i32 > > ,
24+ }
25+
26+ /**
27+ * `&self` means the method takes an immutable reference.
28+ * If you need a mutable reference, change it to `&mut self` instead.
29+ */
30+ impl KthLargest {
31+ fn new ( k : i32 , nums : Vec < i32 > ) -> Self {
32+ let k = k as usize ;
33+ let mut heap = BinaryHeap :: new ( ) ;
34+ for n in nums {
35+ heap. push ( Reverse ( n) ) ;
36+ if heap. len ( ) > k {
37+ heap. pop ( ) ;
38+ }
39+ }
40+ Self { k, nums : heap }
41+ }
42+
43+ fn add ( & mut self , val : i32 ) -> i32 {
44+ self . nums . push ( Reverse ( val) ) ;
45+ if self . nums . len ( ) > self . k {
46+ self . nums . pop ( ) ;
47+ }
48+ self . nums . peek ( ) . unwrap ( ) . 0
49+ }
50+ }
51+
52+ // Your KthLargest object will be instantiated and called as such:
53+ // let obj = KthLargest::new(k, nums);
54+ // let ret_1: i32 = obj.add(val);
You can’t perform that action at this time.
0 commit comments