采集果实
难度:
标签:
题目描述
English description is not available for the problem. Please switch to Chinese.
代码结果
运行时间: 34 ms, 内存: 16.4 MB
/*
题目思路:
1. 使用 Java Stream API 处理数组。
2. 计算每一批次的采集时间,并累加所有批次的采集时间。
*/
import java.util.Arrays;
public class FruitCollectionStream {
public int minTimeToCollectFruits(int[] time, int[][] fruits, int limit) {
return Arrays.stream(fruits)
.mapToInt(fruit -> {
int type = fruit[0];
int num = fruit[1];
int rounds = (num + limit - 1) / limit; // 向上取整计算需要采集的次数
return rounds * time[type];
})
.sum();
}
public static void main(String[] args) {
FruitCollectionStream fc = new FruitCollectionStream();
int[] time = {2, 3, 2};
int[][] fruits = {{0, 2}, {1, 4}, {2, 1}};
int limit = 3;
System.out.println(fc.minTimeToCollectFruits(time, fruits, limit)); // 输出 10
}
}
解释
方法:
The solution iterates through each batch of fruits specified in the 'fruits' list. For each batch, it calculates the number of times the hero needs to collect fruits of that type to meet the required quantity. This is done by dividing the number of fruits needed ('number') by the maximum number of fruits that can be collected in one go ('limit'), and taking the ceiling of the result to ensure that we account for any remaining fruits that don't make up a full 'limit'. The time taken for each batch is then calculated by multiplying the number of times the hero needs to collect fruits by the time it takes to collect one batch of fruits of that type ('time[fruit]'). The total time taken ('ans') is the sum of the times taken for all batches.
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
如何处理当`num`不是`limit`的整数倍时的多余果实?
▷🦆
在计算需要采集的次数时,为什么需要使用向上取整的方式(ceil函数)?
▷🦆
给定的`time`数组在算法中如何与`fruits`数组中的果实类型相对应?
▷