Minimum Swaps to Group All 1‘s Together

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 <= data.length <= 105
  • data[i] is either 0 or 1.

思路:同向双指针的sliding window,

Thinking about it: the final result we want is a window with length of n (total number of the 1s)
Check all the window with the same length n, find the maximum one which already contains the most 1s.
All we need to do is to swap the rest: n-max.

统计总共有多少个1,比如是n,然后找出最大length也就是n window的max 1的count,然后一减去,就是需要swap的最小数量。

class Solution {
    public int minSwaps(int[] A) {
        if(A == null || A.length == 0) {
            return 0;
        }
        int count = 0;
        for(int num: A) {
            if(num == 1) {
                count++;
            }
        }
        
        int curcount = 0;
        int j = 0;
        int max = 0;
        for(int i = 0; i < A.length; i++) {
            while(j < A.length && j - i < count) {
                if(A[j] == 1) {
                    curcount++;
                }
                j++;
            }
            max = Math.max(max, curcount);
            if(j == A.length) {
                break;
            }
            // move i;
            if(A[i] == 1) {
                curcount--;
            }
        }
        return count - max;
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值