【leetcode】1004. Max Consecutive Ones III
阿新 • • 發佈:2019-03-04
int 2-2 block [] value 出現 change bsp 子數組
題目如下:
Given an array
A
of 0s and 1s, we may change up toK
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 <= A.length <= 20000
0 <= K <= A.length
A[i]
is0
or1
解題思路:如果我們把所有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
【leetcode】1004. Max Consecutive Ones III