从结果来看, boxes中的任意一位index中的元素如果为1,则向右边挪动到index+1的cost是1,index+2的cost是2,直到Len(boxes) - 1。同理此位置的1向左边挪动也是同理的cost产生。于是从左向右遍历一次,找到一个1,则往结果数组中以找到1的index+1为起始点,顺序增加cost。从左往右的cost计算则把res数组和boxes数组反过来,重复以上过程。
class Solution:
def minOperations(self, boxes: str) -> List[int]:
N = len(boxes)
res = [0]*N
for index, num in enumerate(boxes):
if num == "1" and index != N-1:
add = 1
for j in range(index+1, N):
res[j] += add
add += 1
boxes = boxes[::-1]
res = res[::-1]
for index, num in enumerate(boxes):
if num == "1" and index != N-1:
add = 1
for j in range(index+1, N):
res[j] += add
add += 1
res = res[::-1]
return res