LeetCode 题解工作台
最少交换次数来组合所有的 1 II
交换 定义为选中一个数组中的两个 互不相同 的位置并交换二者的值。 环形 数组是一个数组,可以认为 第一个 元素和 最后一个 元素 相邻 。 给你一个 二进制环形 数组 nums ,返回在 任意位置 将数组中的所有 1 聚集在一起需要的最少交换次数。 示例 1: 输入: nums = [0,1,0,…
2
题型
8
代码语言
3
相关题
当前训练重点
中等 · 滑动窗口(状态滚动更新)
答案摘要
我们先统计数组中 的个数,记为 ,那么题目实际上就是求一个长度为 的环形子数组,使得子数组中 的个数最多,那么最少交换次数就是 减去子数组中 的个数最多的那个子数组中 的个数。 我们可以使用滑动窗口来解决这个问题,首先统计数组中前 个元素中 的个数,记为 ,然后我们维护一个长度为 的滑动窗口,每次向右移动一个位置,更新 ,同时更新最大的 值,即 $mx = \max(mx, c…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路
题目描述
交换 定义为选中一个数组中的两个 互不相同 的位置并交换二者的值。
环形 数组是一个数组,可以认为 第一个 元素和 最后一个 元素 相邻 。
给你一个 二进制环形 数组 nums ,返回在 任意位置 将数组中的所有 1 聚集在一起需要的最少交换次数。
示例 1:
输入:nums = [0,1,0,1,1,0,0] 输出:1 解释:这里列出一些能够将所有 1 聚集在一起的方案: [0,0,1,1,1,0,0] 交换 1 次。 [0,1,1,1,0,0,0] 交换 1 次。 [1,1,0,0,0,0,1] 交换 2 次(利用数组的环形特性)。 无法在交换 0 次的情况下将数组中的所有 1 聚集在一起。 因此,需要的最少交换次数为 1 。
示例 2:
输入:nums = [0,1,1,1,0,0,1,1,0] 输出:2 解释:这里列出一些能够将所有 1 聚集在一起的方案: [1,1,1,0,0,0,0,1,1] 交换 2 次(利用数组的环形特性)。 [1,1,1,1,1,0,0,0,0] 交换 2 次。 无法在交换 0 次或 1 次的情况下将数组中的所有 1 聚集在一起。 因此,需要的最少交换次数为 2 。
示例 3:
输入:nums = [1,1,0,0,1] 输出:0 解释:得益于数组的环形特性,所有的 1 已经聚集在一起。 因此,需要的最少交换次数为 0 。
提示:
1 <= nums.length <= 105nums[i]为0或者1
解题思路
方法一:滑动窗口
我们先统计数组中 的个数,记为 ,那么题目实际上就是求一个长度为 的环形子数组,使得子数组中 的个数最多,那么最少交换次数就是 减去子数组中 的个数最多的那个子数组中 的个数。
我们可以使用滑动窗口来解决这个问题,首先统计数组中前 个元素中 的个数,记为 ,然后我们维护一个长度为 的滑动窗口,每次向右移动一个位置,更新 ,同时更新最大的 值,即 ,最后答案就是 。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def minSwaps(self, nums: List[int]) -> int:
k = nums.count(1)
mx = cnt = sum(nums[:k])
n = len(nums)
for i in range(k, n + k):
cnt += nums[i % n]
cnt -= nums[(i - k + n) % n]
mx = max(mx, cnt)
return k - mx
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because the array is traversed once with the sliding window. Space complexity is O(1) since only counters and window indices are maintained. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Mentions circular array handling and sliding window optimization.
- question_mark
Focuses on fixed window size based on total 1's.
- question_mark
Checks understanding of running count updates to minimize swaps.
常见陷阱
外企场景- error
Forgetting to account for the circular nature of the array when sliding the window.
- error
Using a dynamic window size instead of the fixed number of 1's, leading to incorrect swaps count.
- error
Miscounting swaps by not counting zeros in the current window correctly.
进阶变体
外企场景- arrow_right_alt
Minimum swaps to group all 0's together in a circular array using the same sliding window approach.
- arrow_right_alt
Non-circular version where the array ends are not adjacent.
- arrow_right_alt
Find maximum 1's in a subarray of fixed length to determine potential swaps in a circular array.