www.noteanddata.com/leetcode-99… ‘貪心代碼很是簡潔,就是從左向右遍歷, 遇到0就作flip,而後一直到數組結尾就行了!!!’html
/**
* @param {number[]} A
* @param {number} K
* @return {number}
*/
var minKBitFlips = function(A, K) {
let len = A.length;
function flip(index) {
for(let i = 0; i < K; ++i) {
if(index + i >= len) {
return -1;
}
A[index + i] = ~~!A[index + i];
}
return 1;
}
let flipped = 0;
for(let i = 0; i < len; ++i) {
if(A[i] === 0) {
let res = flip(i);
if(res === -1) {
return -1;
}
flipped ++;
}
}
return flipped;
};
複製代碼