2023.7.25 将数组和减半的最少操作次数
贪心,显然每次都削减最大数的一半,可以更快的接近至少削减一半的目标。
可以证明,削减任何不是最大数的一半,都不会优于削减最大数的一半,因为题目要求不是正好减少一半,而是至少减少一半。
所以可以开一个大根堆存储所有的数,每次取出堆顶的数进行减半,然后将减半后的数插入堆中,并且更新答案。
use std::{collections::BinaryHeap, cmp::{Reverse, Ordering}};
#[derive(PartialEq)]
struct MyFloat(f64);
impl Eq for MyFloat {}
impl PartialOrd for MyFloat {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.0.partial_cmp(&other.0)
}
}
impl Ord for MyFloat {
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).unwrap()
}
}
impl Solution {
pub fn halve_array(nums: Vec<i32>) -> i32 {
let mut heap = BinaryHeap::new();
for &x in nums.iter() {
heap.push(MyFloat(x as f64));
}
let (mut res, mut sum) = (0, 0.0);
let mut target = 0.0;
for x in nums {
target += x as f64;
}
target /= 2.0;
while sum < target {
let x = heap.pop().unwrap().0;
res += 1;
sum += x / 2.0;
heap.push(MyFloat(x / 2.0));
}
res
}
}