leetcode刷题记录
想每天刷一到两道题,记录起到一个目录作用即可
(中等4.26)1011.在D天内送达包裹的能力-二分法
二分法,模拟过程题解较为简单,值得参考
class Solution:
def shipWithinDays(self, weights: List[int], D: int) -> int:
length = len(weights)
def load(x):
cur = 0
day = 0
for i in range(length) and day < D:
cur += weights[i]
if cur > x:
day += 1
cur = 0
else:
i += 1
return i >= length
l = sum(weights) // D
r = max(weights) * length // D
while l < r:
m = (l + r) // 2
if load(m):
r = m
else:
l = m + 1
return l
(中等4.27)377.组合总和Ⅳ-动态规划
注意一维dp,且重复计算,还有不重复排列的情况
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
l = len(nums)
dp = [0] * (target + 1)
dp[0] = 1
for i in range(target + 1):
for j in range(l):
if i >= nums[j]:
dp[i] += dp[i - nums[j]]
return dp[target]
(中等4.28)633.平方数之和-双指针
简单的双指针的应用
class Solution:
def judgeSquareSum(self, c: int) -> bool:
i = 0
j = int(math.sqrt(c))
while i <= j:
if i * i + j * j == c:
return True
elif i * i + j * j > c:
j -= 1
else:
i += 1
return False
(困难4.29)403.青蛙过河-动态规划
本题一开始思维固化在一维dp,时间复杂度O(n3),转化为二维dp后,复杂度降为n2
class Solution:
def canCross(self, stones: List[int]) -> bool:
l = len(stones)
dp = [[0] * (l + 1) for col in range(l)]
dp[0][0] = 1
for i in range(l):
j = i - 1
while j >= 0 and stones[i] - stones[j] <= i:
k = stones[i] - stones[j]
dp[i][k] = dp[j][k + 1] or dp[j][k] or dp[j][k - 1]
j -= 1
for i in range(l + 1):
if dp[l - 1][i] == 1:
return True
return False
(中等4.30)137.只出现一次的数字II-位运算
哈希的方法不再赘述,这里强调位运算的应用
class Solution:
def singleNumber(self, nums: List[int]) -> int:
ans = 0
l = len(nums)
v = 0
for i in range(32):
v = sum((j >> i & 1) for j in nums)
ans |= ((v % 3) << i)
if v % 3 == 1:
ans -= (1 << 32)
return ans