题目如下:

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

解题思路:如果我们把所有0所在位置对应的下标存入一个数组inx_0中,例如Example 2的inx_0 = [0,1,4,5,9,12,13,14],因为最多把K个0变成1,要构造出最长的全为1的连续子数组,那么很显然所有进行反转操作的0所对应下标在inx_0中必须是连续的。接下来开始遍历数组A,在K大于0的条件下,遇到1则count_1加1,遇到0的话则K减1并且count_1加1(表示这个0反转成1);如果在K=0的情况下遇到0,那么需要去掉第一个0变成的1和这个0之前连续的1的数量,即count减1(减去第一个0变成1的计数),再减去第一个0前面连续的1的数量i,记为count_1减i。记录count_1出现的最大值,直到数组A遍历完成为止。

代码如下:

class Solution(object):
def longestOnes(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
count_1 = 0
zero_inx = []
res = 0
zero_before = -1
for i in range(len(A)):
if A[i] == 1:
count_1 += 1
else:
zero_inx.append(i)
if K > 0:
K -= 1
count_1 += 1
elif K == 0:
res = max(res,count_1)
first_0 = zero_inx.pop(0)
count_1 -= (first_0 - zero_before - 1)
zero_before = first_0
res = max(res, count_1)
return res

最新文章

  1. Java基础知识点4:继承
  2. spring事务源码研读1
  3. webdriver+python 对三大浏览器的支持
  4. 解决 “invalid resource directory name”, resource “crunch”
  5. xfs文件系统
  6. GraphLab面向机器学习的并行框架『针对图数据处理模型』
  7. #ifdef __cplusplus
  8. 查看library_cache 库缓冲区的命中率
  9. 透明窗口(窗口上面文字图片等内容不透明)的实现(使用SetLayeredWindowAttributes API函数)
  10. js前端分页之jQuery
  11. 【IOS开发】SimPholders的使用
  12. Linux环境进程间通信(一):管道及命名管道
  13. HTML 相同name 传递一个数组
  14. 学习笔记CB002:词干提取、词性标注、中文切词、文档分类
  15. jquery中文档处理的总结
  16. 45)django-分页实现
  17. MyEclipse中同时启动两个tomcat
  18. vue 静态资源 压缩提交自动化
  19. js 深复制一个对象
  20. Windows server利用批处理脚本判断端口, 启动tomcat

热门文章

  1. php 封装原生数据导入的方法(csv文件格式)
  2. 基于Springmvc的登录权限拦截器
  3. SQL 关键字的使用顺序
  4. soj#551 loj#2833 帐篷
  5. 信息安全-OAuth2.0:NuGetFromMicrosoft
  6. spring boot 尚桂谷学习笔记10 数据访问02 mybatis
  7. haskell目录层次
  8. tensorflow|tf.train.slice_input_producer|tf.train.Coordinator|tf.train.start_queue_runners
  9. Hadoop2.2.0在Ubuntu编译失败解决方法
  10. 前后端分离使用 Token 登录解决方案