You have
n
boxes. You are given a binary stringboxes
of lengthn
, whereboxes[i]
is'0'
if theith
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 boxj
ifabs(i - j) == 1
. Note that after doing so, there may be more than one ball in some boxes.Return an array
answer
of sizen
, whereanswer[i]
is the minimum number of operations needed to move all the balls to theith
box.Each
answer[i]
is calculated considering the initial state of the boxes.
我承认我飘了
思路:暴力
如果第 j j j个盒子里装有小球,那么移到到第 i i i个盒子,所需要的操作数为 a b s ( j − i ) abs(j-i) abs(j−i),累加计算总和既可
实现
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;
}
}
复杂度
思路:将所有球移入盒子 i i i所需要的操作数取决于其右侧盒子内的小球和左侧盒子内的小球至其的距离,最终操作数即为距离的累加和。因此盒子 i + 1 i+1 i+1所需要的操作数,可以由盒子 i i i所需要的操作数推出。
实现
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;
}
}
复杂度