public class DayCode {
public static void main(String[] args) {
int[] A = new int[]{0, 1, 0};
int K = 1;
int ans = new DayCode().minKBitFlips(A, K);
System.out.println("ans is " + ans);
}
/**
* https://leetcode-cn.com/problems/minimum-number-of-k-consecutive-bit-flips/
* 时间复杂度O(n * k),空间复杂度O(1)
* @param A
* @param K
* @return
*/
public int minKBitFlips(int[] A, int K) {
int ans = 0;
int n = A.length;
for (int i = 0; i < n; i++) {
if (A[i] == 0) {
if (i + K > n) {
return -1;
}
for (int j = i; j < i + K; j++) {
A[j] ^= 1;
}
ans++;
}
}
return ans;
}
/**
* https://leetcode-cn.com/problems/minimum-number-of-k-consecutive-bit-flips/
* 时间复杂度O(n),空间复杂度O(n)
* @param A
* @param K
* @return
*/
public int minKBitFlipsTwo(int[] A, int K) {
int ans = 0;
Deque<Integer> queue = new LinkedList<>();
for (int i = 0; i < A.length; i++) {
if (queue.size() > 0 && i > queue.peek() + K - 1) {
queue.removeFirst();
}
if (queue.size() % 2 == A[i]) {
if (i + K > A.length) {
return -1;
}
queue.add(i);
ans++;
}
}
return ans;
}
}
评论