其他分享
首页 > 其他分享> > [LeetCode] 1004. Max Consecutive Ones III

[LeetCode] 1004. Max Consecutive Ones III

作者:互联网

Given an array A of 0s and 1s, we may change up to K values from 0 to 1.

Return the length of the longest (contiguous) subarray that contains only 1s. 

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 from 0 to 1.  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. 1 <= A.length <= 20000
  2. 0 <= K <= A.length
  3. A[i] is 0 or 1 

最大连续1的个数 III。

给定一个由若干 0 和 1 组成的数组 A,我们最多可以将 K 个值从 0 变成 1 。返回仅包含 1 的最长(连续)子数组的长度。

这是一道比较典型的滑动窗口类型的题目,我们可以直接套用76题的模板。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int longestOnes(int[] A, int K) {
 3         int start = 0;
 4         int end = 0;
 5         int count = 0;
 6         int res = 0;
 7         while (end < A.length) {
 8             if (A[end] == 0) {
 9                 count++;
10             }
11             while (count > K) {
12                 if (A[start] == 0) {
13                     count--;
14                 }
15                 start++;
16             }
17             res = Math.max(res, end - start + 1);
18             end++;
19         }
20         return res;
21     }
22 }

 

LeetCode中有如下一些题目,求的是连续出现的数字或者字母最长可以组成的子串长度,本质上还是滑动窗口类型的题目。

485. Max Consecutive Ones

487. Max Consecutive Ones II

1004. Max Consecutive Ones III

830. Positions of Large Groups

sliding window相关题目

LeetCode 题目总结

标签:count,end,int,Max,Ones,res,Consecutive
来源: https://www.cnblogs.com/cnoodle/p/14238884.html