原题
https://leetcode-cn.com/problems/max-consecutive-ones-iii/

思路
首先想到的是滑动窗口,right++,遇0,count++,count>k,则left++到移除一个0,count–
然而,提交后,竟然只超过了48%的用户,进行优化
right++,遇0,count++,count>k,则left++,遇0则count–,实则是省去了窗口变小的过程
题解
package com.leetcode.code;
/**
* @Description:
* @ClassName: Code1004
* @Author: ZK
* @Date: 2021/2/19 22:51
* @Version: 1.0
*/
public class Code1004 {
public static void main(String[] args) {
// int[] A = {0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1};
int[] A = {0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1};
System.out.println(longestOnes(A, 3));
System.out.println(longestOnes1(A, 3));
}
public static int longestOnes(int[] A, int K) {
int len = A.length;
int max = 0;
int left = 0;
int right = 0;
int count = 0;
for (right = 0; right < len; right++) {
if (A[right] == 0) {
count++;
while(count > K){
if (A[left++] == 0) {
count--;
}
}
}
max = Math.max(max, right-left+1);
}
return max;
}
public static int longestOnes1(int[] A, int K) {
int len = A.length;
int left = 0;
int right = 0;
int count = 0;
while(right < len){
if (A[right++] == 0) {
count++;
}
if (count > K) {
if (A[left++] == 0) {
count--;
}
}
}
return right-left;
}
}
本文主要探讨了LeetCode第1004题《最长的1子串III》的解决方案。作者首先尝试使用滑动窗口的方法,但在提交后发现效率不高,仅超过了48%的用户。随后,作者对算法进行了优化,通过减少窗口大小调整的过程,提高了效率。最终提供了两种不同的优化解法,实现了在遇到0时直接更新计数器和左指针,从而找到最长的含有不超过K个0的连续1子串。
142

被折叠的 条评论
为什么被折叠?



