0
点赞
收藏
分享

微信扫一扫

LeetCode笔记:Weekly Contest 278

灯火南山 2022-02-01 阅读 83

1. 题目一

给出题目一的试题链接如下:

  • 2154. Keep Multiplying Found Values by Two

1. 解题思路

这一题没啥好说的,直接按照题意暴力检索就行了。

2. 代码实现

给出python代码实现如下:

class Solution:
    def findFinalValue(self, nums: List[int], original: int) -> int:
        nums = set(nums)
        while original in nums:
            original *= 2
        return original

提交代码评测得到:耗时126ms,占用内存14.1MB。

2. 题目二

给出题目二的试题链接如下:

  • 2155. All Divisions With the Highest Score of a Binary Array

1. 解题思路

这一题的思路就是用两个数组分别来保存没有个idx左侧0的总数和右侧1的总数,然后就可以快速地给出答案了。

2. 代码实现

给出python代码实现如下:

class Solution:
    def maxScoreIndices(self, nums: List[int]) -> List[int]:
        n = len(nums)
        zeros = [0 for _ in range(n+1)]
        ones = [0 for _ in range(n+1)]
        for i in range(n):
            zeros[i+1] = zeros[i] if nums[i] == 1 else zeros[i] + 1
            ones[n-1-i] = ones[n-i] if nums[n-1-i] == 0 else ones[n-i] + 1
        _max = max(zeros[i] + ones[i] for i in range(n+1))
        return [i for i in range(n+1) if zeros[i] + ones[i] == _max]

提交代码评测得到:耗时5016ms,占用内存25.6MB。

3. 题目三

给出题目三的试题链接如下:

  • 2156. Find Substring With Given Hash Value

1. 解题思路

这一题考察的就是一个多项式的求和,貌似教科书上就有标准解法,不过这里稍微做了一个变形,所以得反向递推回去就是了……

2. 代码实现

给出python代码实现如下:

class Solution:
    def subStrHash(self, s: str, power: int, modulo: int, k: int, hashValue: int) -> str:
        p = [1 for _ in range(k)]
        for i in range(k-1):
            p[i+1] = (p[i] * power) % modulo 
        
        n = len(s)
        
        def encode(idx):
            return ord(s[idx]) - ord('a') + 1
        
        res = ""
        hashval = 0
        for i in range(k):
            hashval = (hashval + p[k-1-i] * encode(n-1-i)) % modulo
        if hashval == hashValue:
            res = s[n-k:n]
        for i in range(n-k-1, -1, -1):
            hashval = ((hashval - encode(i+k) * p[-1]) * power + encode(i) + modulo) % modulo
            if hashval == hashValue:
                res = s[i:i+k]
        return res

提交代码评测得到:耗时356ms,占用内存15MB。

4. 题目四

给出题目四的试题链接如下:

  • 2157. Groups of Strings

暂时没有啥很好的思路,唉,过年就给自己放个假吧……

有兴趣的读者可以直接看官方解答:

  • https://leetcode-cn.com/problems/groups-of-strings/solution/zi-fu-chuan-fen-zu-by-leetcode-solution-a8dr/

新年快乐!^ - ^

举报

相关推荐

0 条评论