Title
Given an array A consisting of several 0s and 1, we can change up to K values from 0 to 1.
Returns the length of the longest (contiguous) sub-array containing only 1.
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] The
numbers in bold are flipped from 0 to 1, and the longest sub-array length is 6.
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]
Bold numbers are flipped from 0 to 1, The longest sub-array length is 10.
prompt:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] 为 0 或 1
Related Topics Two-pointer Sliding Window
Problem-solving ideas
Although this question is a middle-level question, the idea is still more conventional, and the steps are in the code
Code demo
class Solution {
public int longestOnes(int[] A, int K) {
//记录当前窗口1的数量
int nums1=0;
//窗口的左右两边
int left=0,right=0;
for (right=0;right<A.length;right++)
{
if(A[right]==1)
nums1++;
//如果不满足条件,也就是窗口中1的数量与k(0转化为1)的数量相加小于当前窗口的数目,则滑动窗口
if(nums1+K<right-left+1)
{
//滑动窗口,如果窗口的最左边是1,记得1的数目减去1
if(A[left]==1)
nums1--;
//窗户左移
left++;
}
}
//得出最后结果,窗户在A的最右边,且大一,所以不要加1
return right-left;
}
}
effect
The info
answer was successful:
execution time: 3 ms, defeating 94.07% of Java users
Memory consumption: 39.5 MB, defeating 92.15% of Java users