zoukankan      html  css  js  c++  java
  • 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 placein the array.

    Example 1:

    Input: [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: [0,0,0,1,0]
    Output: 0
    Explanation: 
    Since there is only one 1 in the array, no swaps needed.
    

    Example 3:

    Input: [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].
    

    Note:

    1. 1 <= data.length <= 10^5
    2. 0 <= data[i] <= 1

    intuition: the # of 1s that should be grouped together is the # of 1's the whole array has. every subarray of size ones, need several number of swaps to reach, which is the number of zeros in that subarray. 

    use sliding window, check all the window with the same length n (# of 1s), find the maximum one which already contains the most 1s. then swap the rest: n-max.

    time = O(n), space = O(1)

    class Solution {
        public int minSwaps(int[] data) {
            int numOfOnes = 0;
            for(int num : data) {
                if(num == 1) {
                    numOfOnes++;
                }
            }
            
            int slow = 0, fast = 0, counter = 0, max = 0;   // max # of 1s in current window
            while(fast < data.length) {
                while(fast < data.length && fast - slow < numOfOnes) {  // window size of numOfOnes
                    if(data[fast++] == 1) {
                        counter++;
                    }
                }
                max = Math.max(max, counter);
                if(fast == data.length) {
                    break;
                }
                
                if(data[slow++] == 1) {
                    counter--;
                }
            }
            return numOfOnes - max;
        }
    }
  • 相关阅读:
    [luogu1594]护卫队(dp)
    [luogu1968]美元汇率(dp)
    [NOIP2006]金明的预算方案(dp)
    [caioj1056](相同数列问题)填满型01背包2
    [IPUOJ]混合背包 (dp)
    趣说倍增算法
    [POI2005]BAN-Bank Notes (dp、倍增)
    NOIP考前注意
    SharePoint 2013 App 开发—Auto Hosted 方式
    SharePoint 2013 App 开发—App开发概述
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11397766.html
Copyright © 2011-2022 走看看