「Python3」LeetCode 391场周赛 - 三题选手题解

3099. 哈沙德数

3099. 哈沙德数

思路:所有位上的数字相加,再判断是否能整除

Code

class Solution:
    def sumOfTheDigitsOfHarshadNumber(self, x: int) -> int:
        s = 0
        xx = x
        while x!=0:
            s += x% 10
            x //= 10
        return s if xx % s ==0 else -1

3100. 换水问题 II

3100. 换水问题 II

思路:他的题目描述怪怪的,不如直接看着例子。这题看用例就可以秒

Code

class Solution:
    def maxBottlesDrunk(self, numBottles: int, numExchange: int) -> int:
        full = numBottles
        empty = 0
        exchange = numExchange
        res = 0
        
        while not(full == 0 and empty < exchange) :
            res += full
            empty += full
            full = 0
            while empty >= exchange:
                empty -= exchange
                full += 1
                exchange += 1
            
        return res

3101. 交替子数组计数

思路:最直接的想法就是两层遍历,每次从前往后扫描,判断到A[i]==A[i+1]的时候,就重新进行下一轮循环。不过超时了,给了两个特别长的隐藏用例应该。

那就试着优化一下,一层遍历即可,遍历到A[i]==A[i+1]时,说明i前面都是合法的,可以构成(i+1)*i/2个子数组。

Code

class Solution:
    def countAlternatingSubarrays(self, nums: List[int]) -> int:
        n = len(nums)
        res = 0
        i = 0
        while i < n:
            j = 1
            c = 0
            while i+j<n and (nums[i+j] + nums[i+j-1]) % 2 !=0:
                j += 1
                c += 1
            res += (c*(c+1)//2)

            if c == 0:
                i += 1
            else:
                i += j
                
        return res + n
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值