Given a binary array data, return the minimum number of swaps required to group all 1’s present in the array together in any place in the array.
Example 1:
Input: data = [1,0,1,0,1] Output: 1 Explanation: There are 3 ways to group all 1's together: [1,1,1,0,0] using 1 swap. [0,1,1,1,0] using 2 swaps. [0,0,1,1,1] using 1 swap. The minimum is 1.
Example 2:
Input: data = [0,0,0,1,0] Output: 0 Explanation: Since there is only one 1 in the array, no swaps are needed.
Example 3:
Input: data = [1,0,1,0,1,0,0,1,1,0,1] Output: 3 Explanation: One possible solution that uses 3 swaps is [0,0,0,0,0,1,1,1,1,1,1].
Constraints:
-
<

给定一个二进制数组,求解将所有1聚集在一起所需的最小交换次数。通过滑动窗口策略,计算每个长度为1的子序列所需的交换次数,找到最小值作为答案。利用窗口变化只涉及两端元素,减少重复计算,只需遍历一次数组即可找到最小交换次数。
最低0.47元/天 解锁文章
550

被折叠的 条评论
为什么被折叠?



