Skip to content

Commit

Permalink
Merge pull request #6 from stada526/f/1046
Browse files Browse the repository at this point in the history
1046. Last Stone Weight
  • Loading branch information
stada526 authored Jul 12, 2024
2 parents c95b1ca + 8eb1ffe commit 48d5fb5
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/common/heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub struct MaxHeap {
impl MaxHeap {
pub fn new(array: Vec<i32>) -> Self {
let mut heap = Self { tree: array };
for i in 0..(heap.tree.len() / 2) {
for i in (0..(heap.tree.len() / 2)).rev() {
heap.heapify(i)
}

Expand Down Expand Up @@ -58,6 +58,10 @@ impl MaxHeap {
self.heapify(max_index)
}
}

pub fn len(&self) -> usize {
return self.tree.len();
}
}

#[cfg(test)]
Expand Down
1 change: 1 addition & 0 deletions src/solutions.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
mod s_1046_last_stone_weight;
mod s_110_balanced_binary_tree;
mod s_128_longest_consecutive_sequence;
mod s_143_reorder_list;
Expand Down
35 changes: 35 additions & 0 deletions src/solutions/s_1046_last_stone_weight.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use crate::common::heap::MaxHeap;

struct Solution {}

impl Solution {
pub fn last_stone_weight(stones: Vec<i32>) -> i32 {
let mut max_heap = MaxHeap::new(stones);
while max_heap.len() > 1 {
let y = max_heap.pop().unwrap();
let x = max_heap.pop().unwrap();
let diff = y - x;
if diff != 0 {
max_heap.push(diff)
}
}

return if max_heap.len() == 0 {
0
} else {
max_heap.pop().unwrap()
};
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test() {
let stones = vec![2, 7, 4, 1, 8, 1];
let res = Solution::last_stone_weight(stones);
assert_eq!(res, 1)
}
}

0 comments on commit 48d5fb5

Please sign in to comment.