Skip to content

Commit fe22b8c

Browse files
committed
modify code
1 parent 6813a13 commit fe22b8c

1 file changed

Lines changed: 25 additions & 2 deletions

File tree

src/class07/Code01_CoverMax.java

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public static int maxCover2(int[][] m) {
3636
PriorityQueue<Integer> heap = new PriorityQueue<>();
3737
int max = 0;
3838
for (int i = 0; i < lines.length; i++) {
39-
// lines[i] -> cur 在黑盒中,把<=cur.start 东西都弹出
39+
// lines[i] -> cur 在黑盒中,把<=cur.start 东西都弹出
4040
while (!heap.isEmpty() && heap.peek() <= lines[i].start) {
4141
heap.poll();
4242
}
@@ -65,6 +65,28 @@ public int compare(Line o1, Line o2) {
6565

6666
}
6767

68+
// 和maxCover2过程是一样的
69+
// 只是代码更短
70+
// 不使用类定义的写法
71+
public static int maxCover3(int[][] m) {
72+
// m是二维数组,可以认为m内部是一个一个的一维数组
73+
// 每一个一维数组就是一个对象,也就是线段
74+
// 如下的code,就是根据每一个线段的开始位置排序
75+
// 比如, m = { {5,7}, {1,4}, {2,6} } 跑完如下的code之后变成:{ {1,4}, {2,6}, {5,7} }
76+
Arrays.sort(m, (a, b) -> (a[0] - b[0]));
77+
// 准备好小根堆,和课堂的说法一样
78+
PriorityQueue<Integer> heap = new PriorityQueue<>();
79+
int max = 0;
80+
for (int[] line : m) {
81+
while (!heap.isEmpty() && heap.peek() <= line[0]) {
82+
heap.poll();
83+
}
84+
heap.add(line[1]);
85+
max = Math.max(max, heap.size());
86+
}
87+
return max;
88+
}
89+
6890
// for test
6991
public static int[][] generateLines(int N, int L, int R) {
7092
int size = (int) (Math.random() * N) + 1;
@@ -122,7 +144,8 @@ public static void main(String[] args) {
122144
int[][] lines = generateLines(N, L, R);
123145
int ans1 = maxCover1(lines);
124146
int ans2 = maxCover2(lines);
125-
if (ans1 != ans2) {
147+
int ans3 = maxCover3(lines);
148+
if (ans1 != ans2 || ans1 != ans3) {
126149
System.out.println("Oops!");
127150
}
128151
}

0 commit comments

Comments
 (0)