LeetCode 2134 Minimum Swaps to Group All 1‘s Together II

这篇博客介绍了如何解决 LeetCode 上的一道题目——最小交换次数使所有1相聚。通过分析输入的二进制循环数组,确定1的总数,然后用动态规划的方法找出最少的交换次数。算法复杂度为O(n),空间复杂度为O(1)。文章还给出了具体的Java代码实现。
摘要由CSDN通过智能技术生成

swap is defined as taking two distinct positions in an array and swapping the values in them.

circular array is defined as an array where we consider the first element and the last element to be adjacent.

Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location.

Example 1:

Input: nums = [0,1,0,1,1,0,0]
Output: 1
Explanation: Here are a few of the ways to group all the 1's together:
[0,0,1,1,1,0,0] using 1 swap.
[0,1,1,1,0,0,0] using 1 swap.
[1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array).
There is no way to group all 1's together with 0 swaps.
Thus, the minimum number of swaps required is 1.

Example 2:

Input: nums = [0,1,1,1,0,0,1,1,0]
Output: 2
Explanation: Here are a few of the ways to group all the 1's together:
[1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array).
[1,1,1,1,1,0,0,0,0] using 2 swaps.
There is no way to group all 1's together with 0 or 1 swaps.
Thus, the minimum number of swaps required is 2.

Example 3:

Input: nums = [1,1,0,0,1]
Output: 0
Explanation: All the 1's are already grouped together due to the circular property of the array.
Thus, the minimum number of swaps required is 0.

Constraints:

  • 1 <= nums.length <= 105
  • nums[i] is either 0 or 1.

题目链接:https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/

题目大意:最少交换几次可以让所有'1'连在一起,数组是循环的(头尾相连)

题目分析:因为1的总数是固定的,枚举区间判断即可,0的位置必然要进行一次替换,循环的部分对下标取模即可

4ms,时间击败99.1%

class Solution {
    public int minSwaps(int[] nums) {
        int tot = 0, n = nums.length;
        for (int i = 0; i < n; i++) {
            tot += nums[i];
        }
        int cur = 0;
        for (int i = 0; i < tot; i++) {
            if (nums[i] == 0) {
                cur++;
            }
        }
        int ans = cur;
        for (int i = tot; i < n + tot; i++) {
            cur += nums[i - tot];
            cur -= nums[i % n];
            if (ans > cur) {
                ans = cur;
            }
        }
        return ans;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值