xinyu04

导航

LeetCode 1151 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.

Solution

注意这里的交换 \(swap\) 并不是相邻两个元素的,而是任意位置的都可以。所以我们需要找到一个区间,使得所有1变换到该区间所需要的操作数最少。

所以利用滑动窗口,维护一个窗口。统计里面1的数量,我们需要维护该窗口中最大的1的数量。所以最后用总数量减去窗口中的数量即可

点击查看代码
class Solution {
public:
    int minSwaps(vector<int>& data) {
        int n=data.size();
        int cnt1=0;
        int tot=0;
        for(int i=0;i<n;i++)tot+=data[i];
        
        int win=0;
        for(int i=0;i<n;i++){
            if(i>=tot) cnt1 -= (data[i-tot]);
            cnt1+=data[i];
            win = max(win, cnt1);
        }
        return tot-win;
    }
};

posted on 2022-09-15 04:22  Blackzxy  阅读(10)  评论(0编辑  收藏  举报