File tree Expand file tree Collapse file tree 1 file changed +24
-10
lines changed
solution/src/main/java/com/inuker/solution Expand file tree Collapse file tree 1 file changed +24
-10
lines changed Original file line number Diff line number Diff line change 9
9
10
10
public class MaxConsecutiveOnesII {
11
11
12
- public int findMaxConsecutiveOnes (int [] nums ) {
13
- int max = 0 , zero = 0 , k = 1 ; // flip at most k zero
12
+ /**
13
+ * 这题思路是维护一个窗口[l,h]
14
+ * 这个窗口满足条件为0的个数小于等于k,这样这些0都能翻转成1,窗口的大小就是连续的1的个数了
15
+ * 如果遇到一个新的0,要判断当前窗口的0是否超了,如果超了,则窗口左边要收缩直到0的个数仍小于等于k为止
16
+ */
17
+ public int findMaxConsecutiveOnes (int [] nums , int k ) {
18
+ int max = 0 , zero = 0 ;
14
19
for (int l = 0 , h = 0 ; h < nums .length ; h ++) {
15
- if (nums [h ] == 0 )
20
+ if (nums [h ] == 0 ) {
16
21
zero ++;
17
- while (zero > k )
18
- if (nums [l ++] == 0 )
22
+ }
23
+ while (zero > k ) {
24
+ if (nums [l ++] == 0 ) {
19
25
zero --;
26
+ }
27
+ }
20
28
max = Math .max (max , h - l + 1 );
21
29
}
22
30
return max ;
23
31
}
24
32
25
- // for follow up
26
- public int findMaxConsecutiveOnes2 (int [] nums ) {
27
- int max = 0 , k = 1 ; // flip at most k zero
33
+ /**
34
+ * for follow up
35
+ * follow up的意思是说这是个数据流,不能像上面那样随机访问元素
36
+ * 这里用一个队列保存0元素的index,当新来一个0使得队列的size超过k时,队列要poll一个0
37
+ */
38
+ public int findMaxConsecutiveOnes2 (int [] nums , int k ) {
39
+ int max = 0 ;
28
40
Queue <Integer > zeroIndex = new LinkedList <>();
29
41
for (int l = 0 , h = 0 ; h < nums .length ; h ++) {
30
- if (nums [h ] == 0 )
42
+ if (nums [h ] == 0 ) {
31
43
zeroIndex .offer (h );
32
- if (zeroIndex .size () > k )
44
+ }
45
+ if (zeroIndex .size () > k ) {
33
46
l = zeroIndex .poll () + 1 ;
47
+ }
34
48
max = Math .max (max , h - l + 1 );
35
49
}
36
50
return max ;
You can’t perform that action at this time.
0 commit comments