原题说明
Given an array A
of 0s and 1
s, we may change up to K
values from 0
to 1
.
Return the length of the longest (contiguous) subarray that contains only 1
s.
Example 1:
Input: A =
[1,1,1,0,0,0,1,1,1,1,0], K = 2
Output:6
Explanation:
[1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1]
Bolded numbers were flipped from0
to1
. The longest subarray is underlined.
Example 2:
Input:
A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output:10
Explanation:
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
解题思路
使用双指针解题:
zeros
用来记录我们考察的子序列中将0
变为1
的次数。- 用
right
指针从左向右遍历数组A
,right
指针表示当前我们考察的子序列的最右位置,如果遇到0
,则zeros++
,表示增加一次翻转。 left
指针用来记录当前子序列最左的位置,如果发现zeros > K
, 则将left
向右推进,直到zeros <= K
。
推进过程中,如果遇到0
,则zeros--
,表示当前的0
不在考察子序列当中。left
指针实际上一直在追赶right
。
示例代码 (cpp)
1 | class Solution { |
复杂度分析
时间复杂度: O(n)
空间复杂度: O(1)
归纳总结
我们在Youtube上更新了视频讲解,欢迎关注!