优化 这段代码import java.util.*; public class ActivitySelection { public static void main(String[] args) { int[] start = {1, 3, 0, 5, 8, 5}; int[] end = {2, 4, 6, 7, 9, 9}; int n = start.length; List<Integer> result = new ArrayList<>(); int lastEnd = -1; for (int i = 0; i < n; i++) { if (start[i] >= lastEnd) { result.add(i); lastEnd = end[i]; } } System.out.println("Selected activities: " + result); }
时间: 2023-05-16 17:05:28 浏览: 96
java-concurrent-ways:演示几种用Java实现并发的方法
我建议你可以使用贪心算法来优化这段代码。具体来说,你可以按照活动结束时间的顺序对活动进行排序,然后依次选择结束时间最早的活动,直到所有活动都被选择完为止。这样可以保证选择的活动数量最多,并且每个选择的活动都是合法的。以下是优化后的代码:
import java.util.*;
public class ActivitySelection {
public static void main(String[] args) {
int[] start = {1, 3, 0, 5, 8, 5};
int[] end = {2, 4, 6, 7, 9, 9};
int n = start.length;
List<Integer> result = new ArrayList<>();
int lastEnd = -1;
// 按照结束时间对活动进行排序
List<Integer> sortedActivities = new ArrayList<>();
for (int i = 0; i < n; i++) {
sortedActivities.add(i);
}
Collections.sort(sortedActivities, (a, b) -> end[a] - end[b]);
// 依次选择结束时间最早的活动
for (int i : sortedActivities) {
if (start[i] >= lastEnd) {
result.add(i);
lastEnd = end[i];
}
}
System.out.println("Selected activities: " + result);
}
}
阅读全文