In an array A
containing only 0s and 1s, a K
-bit flip consists of choosing a (contiguous) subarray of length K
and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.
Return the minimum number of K
-bit flips required so that there is no 0 in the array. If it is not possible, return -1
.
Example 1:
Input: A = [0,1,0], K = 1 Output: 2 Explanation: Flip A[0], then flip A[2].
Example 2:
Input: A = [1,1,0], K = 2 Output: -1 Explanation: No matter how we flip subarrays of size 2, we can't make the array become [1,1,1].
Example 3:
Input: A = [0,0,0,1,0,1,1,0], K = 3 Output: 3 Explanation: Flip A[0],A[1],A[2]: A becomes [1,1,1,1,0,1,1,0] Flip A[4],A[5],A[6]: A becomes [1,1,1,1,1,0,0,0] Flip A[5],A[6],A[7]: A becomes [1,1,1,1,1,1,1,1]
Note:
1 <= A.length <= 30000
1 <= K <= A.length
题目理解:
给定一个数组,只由0和1组成,每一次可以将任意程度为K的,连续的子数组进行翻转,即将这个子数组中的0变为1,1变为0,问最少经过多少次翻转,可以将整个数组变得只有1没有0
解题思路:
这一题比较新,网上没有太多的答案,我的解法复杂度较高,但是能AC
由于每一个0一定要经过翻转才能成为1,从数组最左边开始,第一个0一定需要经过一次翻转,而且翻转的时候一定是以这个0位开始的一段子数组,如果不是这样,将会在数组更左边的位置产生0,从而增加翻转次数。每一次找到数组最左边的0,并对以它为开头的子数组进行翻转,直到子数组的长度小于K,检查整个数组,如果没有0,则返回翻转次数,否则返回-1
class Solution {
public int minKBitFlips(int[] A, int K) {
int res = 0;
int len = A.length;
for(int i = 0; i < len && i + K - 1 < len; i++){
if(A[i] == 0){
for(int off = 0; off < K; off++)
A[i + off] = (A[i + off] + 1) % 2;
res++;
}
}
for(int i = len - K; i < len; i++){
if(A[i] == 0)
return -1;
}
return res;
}
}