4:
分类:奇偶
1769:
方法一:暴力 时间复杂度 n^2
class Solution(object):
def minOperations(self, boxes):
"""
:type boxes: str
:rtype: List[int]
"""
res = [0] * len(boxes)
for i in range(len(boxes)):
for j in range(len(boxes)):
if boxes[j] == "1":
res[i] += abs(i - j)
return res
方法二:有点类似于dp 时间复杂度 n
class Solution:
def minOperations(self, boxes):
left, right, operations = int(boxes[0]), 0, 0
for i in range(1, len(boxes)):
if boxes[i] == '1':
right += 1
operations += i
res = [operations]
for i in range(1, len(boxes)):
operations += left - right
if boxes[i] == '1':
left += 1
right -= 1
res.append(operations)
return res