LCP 06

桌上有 n 堆力扣币,每堆的数量保存在数组 coins 中。我们每次可以选择任意一堆,拿走其中的一枚或者两枚,求拿完所有力扣币的最少次数。

 

输入:[4,2,1]

输出:4

解释:第一堆力扣币最少需要拿 2 次,第二堆最少需要拿 1 次,第三堆最少需要拿 1 次,总共 4 次即可拿完。

 

第一遍

思路:先求总数 再除2 四舍五入

class Solution(object):
    def minCount(self, coins):
        """
        :type coins: List[int]
        :rtype: int
        """
        total=0
        for coin in coins:
            total=total+coin
        if(total%2==1):
            total=total+1
        return(total/2)

 

对[1,5,5,6]的会出错 因为每一堆要单独操作

 

第二遍

class Solution(object):
    def minCount(self, coins):
        """
        :type coins: List[int]
        :rtype: int
        """
        ans=0
        for coin in coins:
            if(coin%2==1):
                coin=coin+1
            ans=ans+coin/2
//ans=ans+(coin+1)//2
        return(ans)

 

 官方题解先+1再// 更简单

 

posted on 2023-02-02 10:48  YuhangLiuCE  阅读(23)  评论(0)    收藏  举报

导航