Day49力扣打卡

打卡记录

Day49力扣打卡_第1张图片


需要添加的硬币的最小数量(归纳法)

链接
按着已经加入的数,以此偏移对应距离,从而得到新的连续数,若是出现断层则计入最小次数中,再以此偏移对应距离。

class Solution:
    def minimumAddedCoins(self, coins: List[int], target: int) -> int:
        coins.sort()
        i, s, ans = 0, 1, 0
        while s <= target:
            if i < len(coins) and coins[i] <= s:
                s += coins[i]
                i += 1
            else:
                s *= 2
                ans += 1
        return ans

按要求补齐数组(归纳法)

链接
与上题做法并无二致。

class Solution:
    def minPatches(self, nums: List[int], n: int) -> int:
        i, ans, s = 0, 0, 1
        while s <= n:
            if i < len(nums) and nums[i] <= s:
                s += nums[i]
                i += 1
            else:
                s *= 2
                ans += 1
        return ans

统计完全子字符串(分组循环 + 滑动窗口)

链接
需要枚举滑动窗口的大小。

class Solution:
    def countCompleteSubstrings(self, word: str, k: int) -> int:
        def func(s):
            res = 0
            for m in range(1, 27):
                if k * m > len(s):
                    break
                d = Counter()
                for i, x in enumerate(s):
                    d[x] += 1
                    j = i + 1 - k * m
                    if j >= 0:
                        res += all(c == 0 or c == k for c in d.values())
                        d[s[j]] -= 1
            return res

        n, i, ans = len(word), 0, 0
        while i < n:
            start = i
            i += 1
            while i < n and abs(ord(word[i]) - ord(word[i - 1])) <= 2:
                i += 1
            ans += func(word[start:i])
        return ans

你可能感兴趣的:(leetcode刷题打卡,leetcode,算法,python)