LeetCode 题解工作台
使二进制数组全部等于 1 的最少操作次数 I
给你一个二进制数组 nums 。 你可以对数组执行以下操作 任意 次(也可以 0 次): 选择数组中 任意连续 3 个元素,并将它们 全部反转 。 反转 一个元素指的是将它的值从 0 变 1 ,或者从 1 变 0 。 请你返回将 nums 中所有元素变为 1 的 最少 操作次数。如果无法全部变成 1…
5
题型
5
代码语言
3
相关题
当前训练重点
中等 · 滑动窗口(状态滚动更新)
答案摘要
我们注意到,数组中的第一个为 的位置,一定需要进行一次反转操作,否则无法将其变为 。因此,我们可以顺序遍历数组,每次遇到 ,就将其后两个元素进行反转操作,累计一次操作次数。 遍历结束后,返回答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路
题目描述
给你一个二进制数组 nums 。
你可以对数组执行以下操作 任意 次(也可以 0 次):
- 选择数组中 任意连续 3 个元素,并将它们 全部反转 。
反转 一个元素指的是将它的值从 0 变 1 ,或者从 1 变 0 。
请你返回将 nums 中所有元素变为 1 的 最少 操作次数。如果无法全部变成 1 ,返回 -1 。
示例 1:
输入:nums = [0,1,1,1,0,0]
输出:3
解释:
我们可以执行以下操作:
- 选择下标为 0 ,1 和 2 的元素并反转,得到
nums = [1,0,0,1,0,0]。 - 选择下标为 1 ,2 和 3 的元素并反转,得到
nums = [1,1,1,0,0,0]。 - 选择下标为 3 ,4 和 5 的元素并反转,得到
nums = [1,1,1,1,1,1]。
示例 2:
输入:nums = [0,1,1,1]
输出:-1
解释:
无法将所有元素都变为 1 。
提示:
3 <= nums.length <= 1050 <= nums[i] <= 1
解题思路
方法一:顺序遍历 + 模拟
我们注意到,数组中的第一个为 的位置,一定需要进行一次反转操作,否则无法将其变为 。因此,我们可以顺序遍历数组,每次遇到 ,就将其后两个元素进行反转操作,累计一次操作次数。
遍历结束后,返回答案即可。
时间复杂度 ,其中 为数组 的长度。空间复杂度 。
class Solution:
def minOperations(self, nums: List[int]) -> int:
ans = 0
for i, x in enumerate(nums):
if x == 0:
if i + 2 >= len(nums):
return -1
nums[i + 1] ^= 1
nums[i + 2] ^= 1
ans += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Understanding of sliding window approach with state updates.
- question_mark
Ability to optimize for space and time complexity.
- question_mark
Clear reasoning for edge case handling, especially when no solution is possible.
常见陷阱
外企场景- error
Forgetting to handle the edge case where it's impossible to flip all elements to one, returning an incorrect result.
- error
Not properly adjusting the window size during the iteration, leading to unnecessary operations.
- error
Misunderstanding how the sliding window updates, causing an inefficient solution.
进阶变体
外企场景- arrow_right_alt
Consider a variation where the flip operation can only be applied a limited number of times.
- arrow_right_alt
Handling larger input sizes while maintaining the O(n) time complexity.
- arrow_right_alt
Implementing the solution in a way that minimizes memory usage for large inputs.