LeetCode每日一题(2187. Minimum Time to Complete Trips)

You are given an array time where time[i] denotes the time taken by the ith bus to complete one trip.

Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus.

You are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips.

Example 1:

Input: time = [1,2,3], totalTrips = 5
Output: 3

Explanation:

  • At time t = 1, the number of trips completed by each bus are [1,0,0].
    The total number of trips completed is 1 + 0 + 0 = 1.
  • At time t = 2, the number of trips completed by each bus are [2,1,0].
    The total number of trips completed is 2 + 1 + 0 = 3.
  • At time t = 3, the number of trips completed by each bus are [3,1,1].
    The total number of trips completed is 3 + 1 + 1 = 5.
    So the minimum time needed for all buses to complete at least 5 trips is 3.

Example 2:

Input: time = [2], totalTrips = 1
Output: 2

Explanation:
There is only one bus, and it will complete its first trip at t = 2.
So the minimum time needed to complete 1 trip is 2.

Constraints:

  • 1 <= time.length <= 105
  • 1 <= time[i], totalTrips <= 107

确定时间的最大和最小范围, 然后用二分法进行查找



use std::collections::{HashMap, HashSet};

impl Solution {
    fn trips(times: &Vec<i64>, counts: &HashMap<i64, i64>, time: i64) -> i64 {
        let mut trips = 0;
        for &t in times {
            if t > time {
                break;
            }
            trips += time / t * *counts.get(&t).unwrap();
        }
        trips
    }
    pub fn minimum_time(time: Vec<i32>, total_trips: i32) -> i64 {
        let mut counts = HashMap::new();
        let mut times = HashSet::new();
        for t in time {
            *counts.entry(t as i64).or_insert(0i64) += 1;
            times.insert(t as i64);
        }
        let mut times: Vec<i64> = times.into_iter().collect();
        times.sort();
        let mut min = 1;
        let mut max = total_trips as i64 * *times.last().unwrap();
        while min < max {
            let mid = (min + max) / 2;
            let trips = Solution::trips(&times, &counts, mid);
            if trips < total_trips as i64 {
                min = mid + 1;
                continue;
            }
            max = mid;
        }
        min
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值