最少交换次数来组合所有的 1 II
难度:
标签:
题目描述
代码结果
运行时间: 85 ms, 内存: 21.0 MB
/*
* 题目思路:
* 1. 计算总的 1 的数量 totalOnes。
* 2. 利用 Stream 计算总的 1 的数量,以及滑动窗口中的 1 的数量。
* 3. 对于数组的每一个位置,计算其滑动窗口中 1 的最大数量。
*/
import java.util.stream.IntStream;
public class MinSwapsStream {
public int minSwaps(int[] nums) {
int totalOnes = (int) IntStream.of(nums).filter(num -> num == 1).count();
int n = nums.length;
int maxOnes = IntStream.range(0, totalOnes)
.map(i -> nums[i])
.sum();
int currentOnes = maxOnes;
for (int i = 1; i < n; i++) {
currentOnes += nums[(i + totalOnes - 1) % n] - nums[i - 1];
maxOnes = Math.max(maxOnes, currentOnes);
}
return totalOnes - maxOnes;
}
}
解释
方法:
The solution uses a sliding window approach. First, it counts the number of 1s in the array and duplicates the array to handle the circular nature. Then, it creates a window of size equal to the number of 1s and slides it across the array to find the maximum number of 1s that can be gathered in one window. The minimum number of swaps is then calculated by subtracting this maximum from the total count of 1s.
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
为什么先统计数组中`1`的数量再将数组翻倍,翻倍的目的是什么?
▷🦆
在使用滑动窗口法时,如何处理环形数组的边界条件?
▷🦆
在计算滑动窗口中的1的数量时,为什么通过`cnt_ += nums[i + cnt] - nums[i]`更新计数,这种更新方式的正确性如何保证?
▷🦆
请解释为什么最少交换次数是通过`cnt - ans`计算得到的?这里的`ans`代表什么?
▷