@@ -28,20 +28,20 @@ public static void main(String[] args) {
28
28
// lines[i][0]: 第i条线的终点
29
29
// 时间复杂度O(n*(max - min))
30
30
public static int maxCover (int [][] lines ) {
31
- if (null == lines || lines .length < 1 ) {
31
+ if (null == lines || lines .length < 1 ) {
32
32
return 0 ;
33
33
}
34
34
int min = lines [0 ][0 ];
35
35
int max = lines [0 ][1 ];
36
36
for (int i = 1 ; i < lines .length ; i ++) {
37
- min = Math .min (lines [i ][0 ],min );
38
- max = Math .max (lines [i ][1 ],max );
37
+ min = Math .min (lines [i ][0 ],min );
38
+ max = Math .max (lines [i ][1 ],max );
39
39
}
40
40
int maxCover = 0 ;
41
- for (int i = min ; i <= max ; i ++) {
41
+ for (int i = min ; i <= max ; i ++) {
42
42
int cover = 0 ;
43
43
for (int [] line : lines ) {
44
- if (line [0 ] <= i && i <= line [1 ]){
44
+ if (line [0 ] <= i && i <= line [1 ]){
45
45
cover ++;
46
46
}
47
47
}
@@ -52,27 +52,29 @@ public static int maxCover(int[][] lines) {
52
52
53
53
// 堆解法
54
54
// O(N*logN)
55
- public static int maxCover3 (int [][] lines ) {
56
- if (null == lines || lines .length == 0 ) {
55
+ public static int maxCover2 (int [][] lines ) {
56
+ if (lines == null || lines .length < 1 ) {
57
57
return 0 ;
58
58
}
59
- // 开始位置排序
60
- Arrays .sort (lines , Comparator . comparingInt ( line -> line [0 ]) );
61
- PriorityQueue <int []> heap = new PriorityQueue <>(Comparator . comparingInt ( line -> line [1 ]) );
59
+ // 按开始位置排序
60
+ Arrays .sort (lines , 0 , lines . length , ( a , b ) -> a [0 ] - b [ 0 ] );
61
+ PriorityQueue <int []> heap = new PriorityQueue <>(( a , b ) -> a [1 ] - b [ 1 ] );
62
62
int max = 0 ;
63
63
for (int [] line : lines ) {
64
- while (!heap .isEmpty () && heap .peek ()[1 ] < line [0 ]) {
64
+ // 开始位置从小到大
65
+ while (!heap .isEmpty () && line [0 ] > heap .peek ()[1 ]) {
65
66
heap .poll ();
66
67
}
67
68
heap .offer (line );
68
- max = Math .max (heap .size (), max );
69
+ max = Math .max (max , heap .size ());
69
70
}
70
71
return max ;
71
72
}
72
73
74
+
73
75
// 线段树解法
74
76
// 复杂度是:O(N*logN)
75
- public static int maxCover2 (int [][] lines ) {
77
+ public static int maxCover3 (int [][] lines ) {
76
78
HashMap <Integer , Integer > map = index (lines );
77
79
int N = map .size ();
78
80
SegmentTree tree = new SegmentTree (N );
@@ -102,7 +104,6 @@ public static HashMap<Integer, Integer> index(int[][] lines) {
102
104
return map ;
103
105
}
104
106
105
-
106
107
// [1...3],[2..6],[4..9],问:哪个区间描的最多,可以用线段树(注意离散化,注意在范围内+1以后,执行的不是querySum而是queryMax)
107
108
// 注意:不管什么线段,开始位置排序,线段开始位置越早,越先处理
108
109
public static class SegmentTree {
0 commit comments