一刷 07/2022
Version #1 Sliding Window
感觉很难,照着答案写还是一知半解的感觉
Time O(N)
Space O(N)
class Solution {
public int minKBitFlips(int[] nums, int k) {
// number of flips in the sliding window
int flipCounter = 0;
int flips = 0;
boolean[] isFlipped = new boolean[nums.length];
for (int i = 0; i < nums.length; i++) {
if (i >= k && isFlipped[i - k]) {
flipCounter--;
}
// check if we need to flip current bit
if (flipCounter % 2 == nums[i]) {
if (i + k > nums.length) {
return -1;
}
isFlipped[i] = true;
flipCounter++;
flips++;
}
}
return flips;
}
}
No comments:
Post a Comment