Minimum Number of K Consecutive Bit Flips

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. 1 <= A.length <= 30000
  2. 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;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值