第八章 贪心(一)
主要内容
贪心题目
455.分发饼干
思路分析
直接模拟
代码
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g = sorted(g)
s = sorted(s)
gl, sl = len(g), len(s)
i, j = 0, 0
while i < gl and j < sl:
if s[j] < g[i]:
j += 1
else:
i += 1
j += 1
return i
376. 摆动序列
思路分析
保持区间波动,只需要把单调区间上的元素移除就可以了。
代码
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
prediff = 0
result = 1
for i in range(1, len(nums)):
curdiff = nums[i] - nums[i - 1]
# 找波峰、波谷
if (curdiff > 0 and prediff <= 0) or (curdiff < 0 and prediff >= 0):
prediff = curdiff
result += 1
return result
53. 最大子序和
思路分析
代码
class Solution:
# 贪心算法,遇到子和为负数,立马舍弃
def maxSubArray(self, nums: List[int]) -> int:
result = -float('inf')
count = 0
for num in nums:
count += num
if count > result:
result = count
if count <= 0:
count = 0
return result
class Solution:
# 动态规划
def maxSubArray(self, nums: List[int]) -> int:
dp = [-float('inf')] * len(nums)
dp[0] = nums[0]
for i in range(1, len(nums)):
dp[i] = max(dp[i-1]+nums[i], nums[i])
return max(dp)
数组题目(复习)
977.有序数组的平方
思路分析
代码
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
res = [0] * len(nums)
i, j = 0, len(nums) - 1
index = len(nums) - 1
while i <= j:
if nums[i] * nums[i] > nums[j] * nums[j]:
res[index] = nums[i] * nums[i]
i += 1
else:
res[index] = nums[j] * nums[j]
j -= 1
index -= 1
return res
209.长度最小的子数组
思路分析
滑动窗口,终点一直动,当满足和>target后,起点动
代码
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
if not nums:
return 0
# 看有没有被更新过
res = len(nums) + 1
i = j = 0
total = 0
while j < len(nums):
total += nums[j]
j += 1
while total >= target:
res = min(res, j - i)
total -= nums[i]
i += 1
if res == len(nums) + 1:
return 0
else:
return res
59.螺旋矩阵II
思路分析
上右下左顺序填充
代码
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
# 返回结果
res = [[0]*n for _ in range(n)]
# 填充的数
r = 1
# 左闭右闭
start, end = 0, n-1
while start < end and r < n*n:
# 上
for j in range(start, end):
res[start][j] = r
r += 1
# 右
for i in range(start, end):
res[i][end] = r
r += 1
# 下
for j in range(end,start,-1):
res[end][j] = r
r += 1
# 左
for i in range(end,start,-1):
res[i][start] = r
r += 1
start += 1
end -= 1
# 奇数
if n % 2:
res[n//2][n//2] = n*n
return res