Leetcode 1769. Minimum Number of Operations to Move All Balls to Each Box

Posted Black_Knight

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1769. Minimum Number of Operations to Move All Balls to Each Box相关的知识,希望对你有一定的参考价值。

You have n boxes. You are given a binary string boxes of length n, where boxes[i] is \'0\' if the ith box is empty, and \'1\' if it contains one ball.

In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes.

Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box.

Each answer[i] is calculated considering the initial state of the boxes.

 Example 1:

Input: boxes = "110"
Output: [1,1,3]
Explanation: The answer for each box is as follows:
1) First box: you will have to move one ball from the second box to the first box in one operation.
2) Second box: you will have to move one ball from the first box to the second box in one operation.
3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.

Example 2:

Input: boxes = "001011"
Output: [11,8,5,4,3,4]

 Constraints:

  • n == boxes.length
  • 1 <= n <= 2000
  • boxes[i] is either \'0\' or \'1\'.

【问题分析】

给定一列盒子,盒子中装有小球用1表示,盒子为空用0表示,在相邻的盒子间移动一次小球是一次操作,对于每一个盒子,如果把其他盒子的小球都移动到当前盒子需要多少次操作?

【解体思路】

对于每一个盒子,分为两步,一、把它左边盒子的小球都移动到当前盒子,二、把它右边盒子的小球都移动到当前盒子。

我们首先计算从左往右移动,对于每一个盒子n,f(n) = f(n-1) + count(n-1); f(n-1)表示把盒子n-1左边的球移动到盒子n-1需要多少步,count(n-1)表示盒子n左边一共有多少个小球。因为要把小球移动到盒子n,需要先把所有小球移动到盒子n-1,然后再把盒子n-1中所有的小球都移动到盒子n,把盒子n-1中的小球移动到盒子n,每个小球只需要一次操作,因此总共操作次数就是f(n-1) + count(n-1)。

同理可以计算从右往左移动,然后把两次移动的值相加即可。

【Java代码】

class Solution {
    public int[] minOperations(String boxes) {
        int[] res = new int[boxes.length()];
        for(int i = 0, box = 0, opt = 0; i < boxes.length(); i++) {
            res[i] += opt;
            box += boxes.charAt(i) == \'1\' ? 1 : 0;
            opt += box;
        }
        for(int i = boxes.length() - 1, box = 0, opt = 0; i >= 0; i--) {
            res[i] += opt;
            box += boxes.charAt(i) == \'1\' ? 1 : 0;
            opt += box;
        }
        return res;
    }
}

 

以上是关于Leetcode 1769. Minimum Number of Operations to Move All Balls to Each Box的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 1769. 移动所有球到每个盒子所需的最小操作数

Leetcode-462 Minimum Moves to Equal Array Elements II(最少移动次数使数组元素相等 II)

LeetCode 1769 移动所有球到每个盒子所需的最小操作数[数组] HERODING的LeetCode之路

LeetCode Minimum Height Trees

leetcode:Minimum Subarray

leetcode@ [310] Minimum Height Trees