本文主要是介绍Leetcode 1769. Minimum Number of Operations to Move All Balls to Each Box [Python],希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
从结果来看, 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]*Nfor index, num in enumerate(boxes):if num == "1" and index != N-1:add = 1for j in range(index+1, N):res[j] += addadd += 1boxes = boxes[::-1]res = res[::-1]for index, num in enumerate(boxes):if num == "1" and index != N-1:add = 1for j in range(index+1, N):res[j] += addadd += 1res = res[::-1]return res
这篇关于Leetcode 1769. Minimum Number of Operations to Move All Balls to Each Box [Python]的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!