zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    C#基元类型、引用类型和值类型
    UML类图中泛化、实现、依赖、关联、聚合、组合关系
    简述:聚集索引和非聚集索引的区别
    面向对象编程的三特性、七原则和六视点
    设计模式学习笔记——解释器模式(Interpreter)
    设计模式学习笔记——组合模式(Composite)
    程序员编程利器:20款最好的免费的IDEs和编辑器
    奇技淫巧之浏览器秒秒钟变编辑器
    前端技术Jquery与Ajax使用总结
    Chrome也疯狂之Vimium插件
  • 原文地址:https://www.cnblogs.com/liujinhong/p/14810514.html
Copyright © 2011-2022 走看看