可否用java代码展示
时间: 2024-02-24 22:53:15 浏览: 18
当然可以,以下是Java代码示例,实现了与前面Python代码类似的贪心算法:
```java
import java.util.Arrays;
public class TaskScheduling {
public static int taskScheduling(int n, int[] t, int[] k) {
// 将任务按照最后提交时间从小到大排序
int[][] tasks = new int[n][2];
for (int i = 0; i < n; i++) {
tasks[i] = new int[]{t[i], k[i]};
}
Arrays.sort(tasks, (a, b) -> a[0] - b[0]);
// 初始化当前时间和总扣分
int curTime = 0, totalPenalty = 0;
// 依次完成每个任务
for (int[] task : tasks) {
// 计算当前任务的扣分
int penalty = curTime > task[0] ? task[1] : 0;
// 更新当前时间和总扣分
curTime = Math.max(curTime, task[0]) + 1;
totalPenalty += penalty;
}
return totalPenalty;
}
public static void main(String[] args) {
int n = 3;
int[] t = new int[]{1, 3, 1};
int[] k = new int[]{6, 2, 3};
System.out.println(taskScheduling(n, t, k)); // 输出:5
}
}
```
在Java代码中,我们使用了lambda表达式来实现按照最后提交时间从小到大排序的比较器。同时,我们也使用了Java的数组和Math库函数来简化代码实现。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)