File tree Expand file tree Collapse file tree 1 file changed +81
-0
lines changed Expand file tree Collapse file tree 1 file changed +81
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 1. 线段覆盖问题, 使用贪心算法
3
+ * 2. 先将线段按从小到大排序
4
+ * 3. 首先找到第一根线
5
+ * a. 如果第一根线 > 0, 则不能全覆盖, 返回 -1
6
+ * b. 找到 line[0] <= 0 && line1[1] 最大的那根线, 作为第一根线
7
+ * 4. 循环找到能和上一根线连上, 并且右端点最大的线
8
+ * a. 如果存在满足条件的线, 则计数加一
9
+ * b. 如果不存在, 则说明连接不上, 返回 -1
10
+ * c. 如果连接当前线后, 已经 >= n 达到末尾了, 则中断循环
11
+ * 5. 返回计数值
12
+ */
13
+
14
+ /**
15
+ * @param {number } n
16
+ * @param {number[] } ranges
17
+ * @return {number }
18
+ */
19
+ var minTaps = function ( n , ranges ) {
20
+ const lines = [ ] ;
21
+ for ( let i = 0 ; i < ranges . length ; i ++ ) {
22
+ lines . push ( [ i - ranges [ i ] , i + ranges [ i ] ] ) ;
23
+ }
24
+ lines . sort ( ( a , b ) => {
25
+ if ( a [ 0 ] < b [ 0 ] ) {
26
+ return - 1 ;
27
+ } else if ( a [ 0 ] > b [ 0 ] ) {
28
+ return 1 ;
29
+ } else {
30
+ return a [ 1 ] < b [ 1 ] ? - 1 : 1 ;
31
+ }
32
+ } )
33
+
34
+ if ( lines [ 0 ] [ 0 ] > 0 ) {
35
+ return - 1 ;
36
+ }
37
+
38
+ let current = null ;
39
+ while ( lines . length ) {
40
+ if ( lines [ 0 ] [ 0 ] <= 0 ) {
41
+ const line = lines . shift ( ) ;
42
+ if ( current === null || line [ 1 ] > current [ 1 ] ) {
43
+ current = line ;
44
+ }
45
+ } else {
46
+ break ;
47
+ }
48
+ }
49
+ let result = 1 ;
50
+
51
+ if ( current [ 1 ] >= n ) {
52
+ return result ;
53
+ }
54
+
55
+ while ( lines . length ) {
56
+ let max = null ;
57
+ while ( lines . length && lines [ 0 ] [ 0 ] <= current [ 1 ] ) {
58
+ const line = lines . shift ( ) ;
59
+ if ( ! max ) {
60
+ max = line ;
61
+ } else {
62
+ if ( line [ 1 ] > max [ 1 ] ) {
63
+ max = line ;
64
+ }
65
+ }
66
+ }
67
+
68
+ if ( ! max ) {
69
+ return - 1 ;
70
+ }
71
+
72
+ result ++ ;
73
+ current = max ;
74
+
75
+ if ( current [ 1 ] >= n ) {
76
+ break ;
77
+ }
78
+ }
79
+
80
+ return result ;
81
+ } ;
You can’t perform that action at this time.
0 commit comments