Given an array of 0 and 1, find minimum no. of swaps to bring all 1s together (only adjacent swaps allowed)

前端 未结 4 611
生来不讨喜
生来不讨喜 2020-12-19 16:52

If given an array of 1\'s and 0\'s, what\'s good algorithm to show the minimum number of adjacent swaps needed to group all of the 1\'s together. The 1\'s don\'t need to be

4条回答
  •  旧巷少年郎
    2020-12-19 17:28

    UPDATED:

    The algorithm determines center by just getting an array of all indices of 1's. The center of that array will always hold the center index. Much faster.

    oneIndices = array of indices of all 1's in the input
    middleOfOnesIndices = round(oneIndices.length/2)-1    // index to the center index
    minimumSwaps = 0
    foreach index i of oneIndices
        minimumSwaps += aboluteValue(oneIndices[middleOfOneIndices]-oneIndices[i])-absoluteValue(middleOfOneIndices-i);
    

    Here's a fiddle to see it in action:

    https://jsfiddle.net/3pmwrk0d/6/

    This was a fun one. Thanks for the question.

提交回复
热议问题