本文是为了记录做题思路,便于之后优化。
先是利用的最大值与最小值来作为每次取水的杯子,然后利用迭代,每次把归零之后的被子清空,之后再输出出来便于自己理解,具体代码如下:
amount = [5,4,4]
count=0
while True:
count+=1
a=amount.index(max(amount))
b=amount.index(min(amount))
if a!=b:
amount[a]-=1
amount[b]-=1
else:
amount[0]-=1
print(f'maxindex={a}')
print(f'minindex={b}')
if amount[a]==0:
break
if amount[b]==0:
amount.remove(0)
print(amount)
print(count)
输出的数值如下:
maxindex=0
minindex=1
[4, 3, 4]
maxindex=0
minindex=1
[3, 2, 4]
maxindex=2
minindex=1
[3, 1, 3]
maxindex=0
minindex=1
[2, 3]
maxindex=1
minindex=0
[1, 2]
maxindex=1
minindex=0
[1]
maxindex=0
minindex=0
7
具体数值的话没有太大问题,转接到leetcode里面:
class Solution:
def fillCups(self, amount: List[int]) -> int:
count=0
while True:
count+=1
a=amount.index(max(amount))
b=amount.index(min(amount))
if a!=b:
amount[a]-=1
amount[b]-=1
else:
amount[0]-=1
if amount[a]==0:
break
if amount[b]==0:
amount.remove(0)
return count
执行实例的话倒也都对,但是提交出了问题。
原因是[0,0,0]的时候不能正确输出0,而是一直在循环里面,因为没有任何一个元素是0,第一次迭代之后都变为了-1.
在0这里添加了新的判断try后还是会有问题,所以计划把代码进行一个小幅度的修改,把判断的条件放在最前面,然后根据这个条件不断判断,例如如果都是0的时候就直接返回0,用remove把0去掉之后再判断那样子:
amount = [0,0,0]
count=0
while True:
print(amount)
try:
while True:
amount.remove(0)
break
except:
if not amount:
break
count+=1
a=amount.index(max(amount))
b=amount.index(min(amount))
if a!=b:
amount[a]-=1
amount[b]-=1
else:
amount[0]-=1
print(f'maxindex={a}')
print(f'minindex={b}')
if amount[a]==0:
break
print(count)
转移到leetcode中,代码如下:
class Solution:
def fillCups(self, amount: List[int]) -> int:
count=0
while True:
try:
while True:
amount.remove(0)
break
except:
if not amount:
break
count+=1
a=amount.index(max(amount))
b=amount.index(min(amount))
if a!=b:
amount[a]-=1
amount[b]-=1
else:
amount[0]-=1
if amount[a]==0:
break
return count
[0, 2, 2]
maxindex=0
minindex=0
[1, 2]
maxindex=1
minindex=0
[0, 1]
maxindex=0
minindex=0
3
输出出来发现由于两个数一样大,所以处理的时候只有一个再自己减少。参考了一些评论,之后发现自己的思路与某个评论一致,即取出来其中最大的两个数,直到只剩下一个,再慢慢取出来,于是按照这个思路修改自己代码:
amount = [0,5,4]
count=0
while True:
amount=sorted(amount)
print(amount)
if amount[-1]>0:
amount[-1]-=1
count+=1
if amount[-2]>0:
amount[-2]-=1
else:
break
print(count)
把代码转移到Leetcode:
class Solution:
def fillCups(self, amount: List[int]) -> int:
count=0
while True:
amount=sorted(amount)
if amount[-1]>0:
amount[-1]-=1
count+=1
if amount[-2]>0:
amount[-2]-=1
else:
break
return count