力扣第 164 场双周赛

本文最后更新于 2 分钟前,文中所描述的信息可能已发生改变。

3663. 出现频率最低的数字 - 力扣(LeetCode)

题目类型

#计数 #数学

解题思路

统计十进制的每个数位个数,从大到小记录最小出现次数

示例代码

python
class Solution:
    def getLeastFrequentDigit(self, n: int) -> int:
        cnt = [0] * 10
        while n:
            cnt[n % 10] += 1
            n //= 10
        mn = inf
        ans = 10
        for i in range(9, -1, -1):
            if cnt[i] and cnt[i] <= mn:
                ans = i
                mn = cnt[i]
        return ans

3664. 两个字母卡牌游戏 - 力扣(LeetCode)

题目类型

#贪心 #枚举 #结论

解题思路

统计可能兼容的字符串个数,枚举可能分配的xx的个数,根据结论判断最大值

参考:枚举 + 结论(Python/Java/C++/Go)

示例代码

python
min = lambda x, y: x if x < y else y
f = lambda x, y: min(x // 2, x - y)
f = cache(f)
class Solution:
    def score(self, cards: List[str], x: str) -> int:
        cnt = [[0] * 26 for _ in range(2)]
        cnt1 = 0
        for card in cards:
            a, b = list(card)
            if x == a and x == b:
                cnt1 += 1
            elif x == a:
                cnt[0][ord(b) - 97] += 1
            elif x == b:
                cnt[1][ord(a) - 97] += 1

        s1 = sum(cnt[0])
        s2 = sum(cnt[1])
        mx1 = max(cnt[0])
        mx2 = max(cnt[1])
        ans = 0
        for i in range(cnt1 + 1):
            ns1 = s1 + i
            ns2 = s2 + cnt1 - i
            nmx1 = max(mx1, i)
            nmx2 = max(mx2, cnt1 - i)
            ans = max(ans, f(ns1, nmx1) + f(ns2, nmx2))

        return ans

3665. 统计镜子反射路径数目 - 力扣(LeetCode)

题目类型

#网格图DP

解题思路

分方向记录子问题状态,然后枚举,遇到镜子则换方向转移,没遇到则可以一起转移

示例代码

python
class Solution:
    def uniquePaths(self, grid: List[List[int]]) -> int:
        MOD = 10 ** 9 + 7
        n, m = len(grid), len(grid[0])
        f = [[0] * 2 for _ in range(m + 1)]
        f[1] = [1, 1]
        for i, row in enumerate(grid):
            for j, x in enumerate(row):
                if x == 0:
                    f[j + 1][0] = (f[j][0] + f[j + 1][1]) % MOD
                    f[j + 1][1] = f[j + 1][0]
                else:
                    f[j + 1][0] = f[j + 1][1]
                    f[j + 1][1] = f[j][0]
        return f[m][0]

3666. 使二进制字符串全为 1 的最少操作次数 - 力扣(LeetCode)

题目类型

#数学 #BFS #有序集合

解题思路

参考:数学做法(Python/Java/C++/Go)

示例代码

python
class Solution:
    def minOperations(self, s: str, k: int) -> int:
        n = len(s)
        z = s.count('0')
        if z == 0:
            return 0
        if n == k:
            return 1 if z == k else -1

        ans = inf
        if z % 2 == 0:
            m = max((z + k - 1) // k, (z + n - k - 1) // (n - k))
            ans = m + m % 2

        if z % 2 == k % 2:
            m = max((z + k - 1) // k, (n - z + n - k - 1) // (n - k))
            ans = min(ans, m | 1)

        return ans if ans < inf else -1
力扣第 466 场周赛
力扣第 465 场周赛