ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[LeetCode] 1004. Max Consecutive Ones III

2021-01-06 03:03:20  阅读:322  来源: 互联网

标签:count end int Max Ones res Consecutive


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有