LeetCode每日一题4.10

2999. 统计强大整数的数目

问题

问题分析

题目要求统计区间 [start, finish] 内满足以下条件的整数数目:

整数的每个数位都小于等于 limit。

整数的末尾部分是字符串 s(即 s 是该整数的后缀)。

关键点:

后缀匹配:需要判断一个整数是否以字符串 s 结尾。

数位限制:每个数位必须小于等于 limit。

区间范围:统计的整数必须在 [start, finish] 范围内。

思路

遍历区间:从 start 到 finish,逐个检查每个整数是否满足条件。

后缀匹配:将整数转换为字符串,检查其是否以 s 结尾。

数位限制:检查整数的每个数位是否小于等于 limit。

计数:统计满足条件的整数数量。

代码

python 复制代码
class Solution:
    def numberOfPowerfulInt(self, start: int, finish: int, limit: int, s: str) -> int:
        count = 0
        # 遍历区间 [start, finish]
        for num in range(start, finish + 1):
            num_str = str(num)
            # 检查是否以 s 结尾
            if not num_str.endswith(s):
                continue
            # 检查每个数位是否 <= limit
            if all(int(digit) <= limit for digit in num_str):
                count += 1
        return count

复杂度分析

时间复杂度:

遍历区间 [start, finish],假设区间长度为 n,每次检查整数的后缀和数位需要 O(k),其中 k 是整数的位数。总时间复杂度为 O(n * k)。(超时)

空间复杂度:

仅使用常量级别的额外空间,空间复杂度为 O(1)。

学习

困难题还是不会做,参考学习

优化时间复杂度:

python 复制代码
class Solution:
    def numberOfPowerfulInt(self, start: int, finish: int, limit: int, s: str) -> int:
        high = list(map(int, str(finish)))  # 避免在 dfs 中频繁调用 int()
        n = len(high)
        low = list(map(int, str(start).zfill(n)))  # 补前导零,和 high 对齐
        diff = n - len(s)

        @cache
        def dfs(i: int, limit_low: bool, limit_high: bool) -> int:
            if i == n:
                return 1

            # 第 i 个数位可以从 lo 枚举到 hi
            # 如果对数位还有其它约束,应当只在下面的 for 循环做限制,不应修改 lo 或 hi
            lo = low[i] if limit_low else 0
            hi = high[i] if limit_high else 9

            res = 0
            if i < diff:  # 枚举这个数位填什么
                for d in range(lo, min(hi, limit) + 1):
                    res += dfs(i + 1, limit_low and d == lo, limit_high and d == hi)
            else:  # 这个数位只能填 s[i-diff]
                x = int(s[i - diff])
                if lo <= x <= hi:  # 题目保证 x <= limit,无需判断
                    res = dfs(i + 1, limit_low and x == lo, limit_high and x == hi)
            return res

        return dfs(0, True, True)

学习来源:

作者:灵茶山艾府

链接:https://leetcode.cn/problems/count-the-number-of-powerful-integers/solutions/2595149/shu-wei-dp-shang-xia-jie-mo-ban-fu-ti-da-h6ci/

来源:力扣(LeetCode)

相关推荐
许愿与你永世安宁2 小时前
力扣343 整数拆分
数据结构·算法·leetcode
爱coding的橙子2 小时前
每日算法刷题Day42 7.5:leetcode前缀和3道题,用时2h
算法·leetcode·职场和发展
YuTaoShao3 小时前
【LeetCode 热题 100】73. 矩阵置零——(解法二)空间复杂度 O(1)
java·算法·leetcode·矩阵
杰克尼4 小时前
1. 两数之和 (leetcode)
数据结构·算法·leetcode
YuTaoShao5 小时前
【LeetCode 热题 100】56. 合并区间——排序+遍历
java·算法·leetcode·职场和发展
JoJo_Way10 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
凌肖战12 小时前
力扣网C语言编程题:在数组中查找目标值位置之二分查找法
c语言·算法·leetcode
GEEK零零七14 小时前
Leetcode 1103. 分糖果 II
数学·算法·leetcode·等差数列
重庆小透明15 小时前
力扣刷题记录【1】146.LRU缓存
java·后端·学习·算法·leetcode·缓存
desssq16 小时前
力扣:70. 爬楼梯
算法·leetcode·职场和发展