码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2021-06-02 10:37:12      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:fir   count   har   amp   you   nat   hat   ini   nts   

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

标签:fir   count   har   amp   you   nat   hat   ini   nts   

原文地址:https://www.cnblogs.com/liujinhong/p/14810514.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!