5993. 将找到的值乘以 2
我的做法是将数组从小到大排序之后,再将找到的值乘以2:
class Solution:def findFinalValue(self, nums: List[int], original: int) -> int:nums.sort()for num in nums:if original == num:original *= 2return original
然而更好的做法应该是使用集合 set,判断数字是否在集合中即可:
class Solution:def findFinalValue(self, nums: List[int], original: int) -> int:s = set(nums)cnt = originalwhile cnt in s:cnt *= 2return cnt
5981. 分组得分最高的所有下标
class Solution:def maxScoreIndices(self, nums: List[int]) -> List[int]:n = len(nums)ans = []temp = 0for i in range(n):ans.append(temp)if nums[i] == 0:temp += 1else:temp -= 1ans.append(temp)maxi = max(ans)return [i for i in range(len(ans)) if ans[i] == maxi]
由题目不难看出,如果把 0 作为 +1 分,1 作为 -1 分,则从左到右分数最高的位置就是最好的划分点,这里注意划分的位置是比数组长度大 1 的。
5994. 查找给定哈希值的子串
class Solution:def subStrHash(self, s: str, power: int, modulo: int, k: int, hashValue: int) -> str:cnt = 0n = len(s)s = s[::-1] # 使用逆序的字符串# 第一个字符串(还差最后一位),所以这里 power 最高只有 k - 2 次for i in range(k - 1):cnt = (cnt * power + (ord(s[i]) - ord('a') + 1)) % moduloans = ""for i in range(k - 1, n):cnt = (cnt * power + (ord(s[i]) - ord('a') + 1)) % modulo # 加上右边的字符if cnt == hashValue: ans = s[i - k + 1 : i + 1]cnt = (cnt - (ord(s[i - k + 1]) - ord('a') + 1) * pow(power, k - 1, modulo) % modulo) % modulo # 减去左边的字符return ans[::-1]
这题如果从左到右直接做的话,肯定会超时。最好的思路应该是将字符串逆序,然后用累加器 cnt 乘以 power 然后加右边的字符 (ord(s[i]) - ord(‘a’) + 1),同时减去左边字符的指数 (ord(s[i - k + 1]) - ord(‘a’) + 1) * pow(power, k - 1, modulo) % modulo,即滑动窗口来代替指数运算。这里应该学习的是 pow 函数:pow(x,y,z) 等价于 x ** y % z