Skip to content

Commit

Permalink
修复 Comparator 的 compare 方法里的溢出问题
Browse files Browse the repository at this point in the history
在 compare 方法里,不能直接使用 a[1] - b[1],因为可能会溢出,目前这种写法在 leetcode 已经不能通过了
  • Loading branch information
zhangxiann authored and labuladong committed Nov 4, 2020
1 parent b4a38fb commit 820a10f
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions 动态规划系列/贪心算法之区间调度问题.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,15 @@ int intervalSchedule(int[][] intvs) {}
public int intervalSchedule(int[][] intvs) {
if (intvs.length == 0) return 0;
// 按 end 升序排序
Arrays.sort(intvs, new Comparator<int[]>() {
Arrays.sort(points, new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
return a[1] - b[1];
// 这里不能使用 a[1] - b[1],要注意溢出问题
if (a[1] < b[1])
return -1;
else if (a[1] > b[1])
return 1;
else return 0;
}
});
// 至少有一个区间不相交
Expand Down

0 comments on commit 820a10f

Please sign in to comment.