Leetcode周赛复盘——第 278 场力扣周赛
生活随笔
收集整理的這篇文章主要介紹了
Leetcode周赛复盘——第 278 场力扣周赛
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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 cnt5981. 分組得分最高的所有下標
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
總結
以上是生活随笔為你收集整理的Leetcode周赛复盘——第 278 场力扣周赛的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 垂直起降固定翼无人机 F120 应急通信
- 下一篇: DDOS技术(ddos常用技术)