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
思路:brote forth,就是greedy,因为flip连续的k个,从左往右,只能遇见0就flip,然后依次循环;如果最后K个,中间有0,直接return -1;O(N^2);
class Solution {
public int minKBitFlips(int[] A, int K) {
int count = 0;
for(int i = 0; i <= A.length - K; i++) {
if(A[i] == 0) {
count++;
flip(A, i, K);
}
}
for(int i = A.length - K; i < A.length; i++) {
if(A[i] == 0) {
return -1;
}
}
return count;
}
private void flip(int[] A, int pos, int K) {
for(int i = pos; i < pos + K; i++) {
A[i] ^= 1;
}
}
}
思路2:跟开关一样,flip偶数次跟没有flip一样,flip奇数次,跟flip一次一样;那么用flipTimes记录[i - k + 1, i - 1] 里面total flip的次数,因为这些点,会作用于i;另外用一个int array记录每个位子flip了1次还是0次;这样flipTimes就是个滑动窗口的做法去记录[i - k + 1, i - 1]的次数,i >= K,flip -= isFlipAt[i - k]; 然后原来A[i]根本不用动,可以分四种情况来讨论是否需要flip,从而记录总共flip的次数;O(N);
class Solution {
public int minKBitFlips(int[] A, int K) {
int n = A.length;
int[] isFlipAt = new int[n];
int flipTimes = 0;
int res = 0;
for(int i = 0; i < n; i++) {
if(i >= K) {
flipTimes -= isFlipAt[i - K];
}
if(A[i] == 1 && flipTimes % 2 == 0) {
continue;
} else if(A[i] == 0 && flipTimes % 2 == 1) {
continue;
} else if(A[i] == 0 && flipTimes % 2 == 0) {
if(i + K > n) return -1;
res++;
isFlipAt[i] = 1;
flipTimes++;
} else if(A[i] == 1 && flipTimes % 2 == 1) {
if(i + K > n) return -1;
res++;
isFlipAt[i] = 1;
flipTimes++;
}
}
return res;
}
}