【每日一题Day44】LC1769移动所有球到每个盒子所需要的最小操作数 | 模拟 贡献

本文介绍了一种高效算法,用于计算将所有球移动到每个盒子所需的最小操作数。通过巧妙利用前后位置的球数量变化,实现了从O(n^2)到O(n)的时间复杂度优化。

移动所有球到每个盒子所需要的最小操作数【LC1769】

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.

我承认我飘了

暴力

  • 思路:暴力

    如果第jjj个盒子里装有小球,那么移到到第iii个盒子,所需要的操作数为abs(j−i)abs(j-i)abs(ji),累加计算总和既可

  • 实现

    class Solution {
        public int[] minOperations(String boxes) {
            int n = boxes.length();
            int[] res = new int[n];
            for (int i = 0; i < n; i++){
                for (int j = 0; j < n; j++){
                    if (boxes.charAt(j) == '1'){
                        res[i] += Math.abs(j - i);
                    }
                }
            }
            return res;
        }
    }
    
    • 复杂度

      • 时间复杂度:O(n2)O(n^2)O(n2)
      • 空间复杂度:O(1)O(1)O(1)

贡献

  • 思路:将所有球移入盒子iii所需要的操作数取决于其右侧盒子内的小球和左侧盒子内的小球至其的距离,最终操作数即为距离的累加和。因此盒子i+1i+1i+1所需要的操作数,可以由盒子iii所需要的操作数推出。

    • 假设所有球移入盒子iii所需要的操作数为resires_iresi,右侧盒子的小球个数为rightiright_irighti,左侧盒子的小球个数为leftileft_ilefti(包括其自身),那么盒子i+1i+1i+1所需要的操作数为resi+lefti−rightires_i+left_i-right_iresi+leftirighti
  • 实现

    class Solution {
        public int[] minOperations(String boxes) {
            int n = boxes.length();
            int[] res = new int[n];
            int left = boxes.charAt(0) - '0';
            int right = 0;
            for (int i = 1; i < n; i++){
                if (boxes.charAt(i) == '1'){
                    right++;
                    res[0] += i;
                }
            }
            for (int i = 1; i < n; i++){
                res[i] = res[i-1] + left - right;
                if (boxes.charAt(i) == '1'){
                    left++;
                    right--;
                }
            }
            return res;
        }
    }
    
    • 复杂度

      • 时间复杂度:O(n)O(n)O(n)
      • 空间复杂度:O(1)O(1)O(1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值