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 99
1010public class MaxConsecutiveOnesII {
1111
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 ;
1419 for (int l = 0 , h = 0 ; h < nums .length ; h ++) {
15- if (nums [h ] == 0 )
20+ if (nums [h ] == 0 ) {
1621 zero ++;
17- while (zero > k )
18- if (nums [l ++] == 0 )
22+ }
23+ while (zero > k ) {
24+ if (nums [l ++] == 0 ) {
1925 zero --;
26+ }
27+ }
2028 max = Math .max (max , h - l + 1 );
2129 }
2230 return max ;
2331 }
2432
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 ;
2840 Queue <Integer > zeroIndex = new LinkedList <>();
2941 for (int l = 0 , h = 0 ; h < nums .length ; h ++) {
30- if (nums [h ] == 0 )
42+ if (nums [h ] == 0 ) {
3143 zeroIndex .offer (h );
32- if (zeroIndex .size () > k )
44+ }
45+ if (zeroIndex .size () > k ) {
3346 l = zeroIndex .poll () + 1 ;
47+ }
3448 max = Math .max (max , h - l + 1 );
3549 }
3650 return max ;
You can’t perform that action at this time.
0 commit comments