一,题目描述
英文描述
Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.
中文描述
给定一个二进制数组 nums
和一个整数 k
,如果可以翻转最多 k
个 0
,则返回 数组中连续 1
的最大个数 。
示例与说明
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/max-consecutive-ones-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二,解题思路
滑动窗口方法
- 当窗口内0的数目<=k,窗口右侧向右移动,扩展窗口;
- 当窗口内0的数目>k,窗口左侧向右移动,收缩窗口;
三,AC代码
Java
class Solution {
public int longestOnes(int[] nums, int k) {
int left = 0;
int right = 0;
int numOfZero = 0;
int ans = 0;
while (right < nums.length) {
if (nums[right] == 0) {
numOfZero++;
}
if (numOfZero <= k) {
ans = Math.max(ans, right - left + 1);
} else {
while(left < right && nums[left] != 0) {
left++;
}
left++;
numOfZero--;
}
right++;// !!!
}
return ans;
}
}
四,解题过程
第一搏
限定区间左右范围,当范围内0数目小于k时,将区间长度与ans比较,并替换
class Solution {
public int longestOnes(int[] nums, int k) {
int n = nums.length;
int ans = 0;
for (int i = 0; i < n; i++) {
int numOfZero = 0;
for (int j = i; j < n; j++) {
if (nums[j] == 0) numOfZero++;
if (numOfZero > k) {
break;
} else {
ans = Math.max(ans, j - i + 1);
}
}
}
return ans;
}
}
O(N^2)时间复杂度,还是超时了
第二搏
滑动窗口yyds