Skip to content

Commit b56b11e

Browse files
committed
feat(heap): add 1046_last_stone_weight.rs
1 parent 883591a commit b56b11e

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,3 +159,4 @@ so that you can use `just tf TEST` command to test.
159159
| Problem | Difficulty | Solution |
160160
| - | - | - |
161161
| 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) |
162+
| 1046. Last Stone Weight | Easy | [1046_last_stone_weight.rs](./tests/1046_last_stone_weight.rs) |

tests/1046_last_stone_weight.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// 1046. Last Stone Weight
2+
// https://leetcode.com/problems/last-stone-weight/description/
3+
// Topics: Heap / Priority Queue.
4+
// Difficulty: Easy.
5+
6+
#![allow(unused)]
7+
8+
#[test]
9+
fn test_1046_last_stone_weight() {}
10+
11+
#[derive(Debug)]
12+
pub struct Solution;
13+
14+
// ---------------------------------
15+
// copy to leetcode starts from here
16+
// ---------------------------------
17+
18+
impl Solution {
19+
pub fn last_stone_weight(stones: Vec<i32>) -> i32 {
20+
use std::collections::BinaryHeap;
21+
let mut heap: BinaryHeap<i32> = BinaryHeap::from(stones);
22+
while heap.len() >= 2 {
23+
let x = heap.pop().unwrap();
24+
let y = heap.pop().unwrap();
25+
let diff = (x - y).abs();
26+
if diff != 0 {
27+
heap.push(diff);
28+
}
29+
}
30+
*heap.peek().unwrap_or(&0)
31+
}
32+
}

0 commit comments

Comments
 (0)