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,K = 2 Output: -1 Explanation: No matter how we flip subarrays of size 2,we can‘t make the array become [1,1].
Example 3:
input: A = [0,K = 3 Output: 3 Explanation: Flip A[0],A[1],A[2]: A becomes [1,0] Flip A[4],A[5],A[6]: A becomes [1,0] Flip A[5],A[6],A[7]: A becomes [1,1]
Note:
1 <= A.length <= 30000
1 <= K <= A.length
在仅包含 0
和 1
的数组 A
中,一次 K
位翻转包括选择一个长度为 K
的(连续)子数组,同时将子数组中的每个 0
更改为 1
,而每个 1
更改为 0
。
返回所需的 K
位翻转的次数,以便数组没有值为 0
的元素。如果不可能,返回 -1
。
示例 1:
输入:A = [0,K = 1输出:2解释:先翻转 A[0],然后翻转 A[2]。
示例 2:
输入:A = [1,K = 2输出:-1解释:无论我们怎样翻转大小为 2 的子数组,我们都不能使数组变为 [1,1]。
示例 3:
输入:A = [0,K = 3输出:3解释:翻转 A[0],A[2]: A变成 [1,0]翻转 A[4],A[6]: A变成 [1,0]翻转 A[5],A[7]: A变成 [1,1]
提示:
1 <= A.length <= 30000
1 <= K <= A.length
Runtime: 752 ms Memory Usage: 19.1 MB 1 class Solution { 2 func minKBitFlips(_ A: [Int],_ K: Int) -> Int { 3 var ans:Int = 0 4 var n:Int = A.count 5 var f:[Bool] = [Bool](repeating:false,count:n + 1) 6 var sum:Bool = false 7 for i in 0..<n 8 { 9 //异或10 sum = (sum == f[i]) ? false : true11 if sum == (A[i] == 1)12 {13 if i + K > n {return -1}14 f[i + K] = !f[i + K]15 sum = !sum16 ans += 117 }18 }19 return ans 20 }21 }总结
以上是内存溢出为你收集整理的[Swift Weekly Contest 124]LeetCode995. K 连续位的最小翻转次数 | Minimum Number of K Consecutive Bit Flips全部内容,希望文章能够帮你解决[Swift Weekly Contest 124]LeetCode995. K 连续位的最小翻转次数 | Minimum Number of K Consecutive Bit Flips所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)