Skip to content

Commit 820a10f

Browse files
zhangxiannlabuladong
authored andcommitted
修复 Comparator 的 compare 方法里的溢出问题
在 compare 方法里,不能直接使用 a[1] - b[1],因为可能会溢出,目前这种写法在 leetcode 已经不能通过了
1 parent b4a38fb commit 820a10f

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

动态规划系列/贪心算法之区间调度问题.md

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,15 @@ int intervalSchedule(int[][] intvs) {}
7272
public int intervalSchedule(int[][] intvs) {
7373
if (intvs.length == 0) return 0;
7474
// 按 end 升序排序
75-
Arrays.sort(intvs, new Comparator<int[]>() {
75+
Arrays.sort(points, new Comparator<int[]>() {
76+
@Override
7677
public int compare(int[] a, int[] b) {
77-
return a[1] - b[1];
78+
// 这里不能使用 a[1] - b[1],要注意溢出问题
79+
if (a[1] < b[1])
80+
return -1;
81+
else if (a[1] > b[1])
82+
return 1;
83+
else return 0;
7884
}
7985
});
8086
// 至少有一个区间不相交

0 commit comments

Comments
 (0)