DW&LeetCode_day10(121、122、124)
写在前面:
- 转眼第十天了,已经写过三十多道题了,不错,继续加油!
开源内容
目录
DW&LeetCode_day10(121、122、124)
学习大纲
121. 买卖股票的最佳时机
题解:
以LeetCode 881救生艇问题为例
由于本题只要求计算出
最小船数
,所以原数组是否被改变,和元素索引位置都不考虑在内,所以可以先对于给定数组进行排序,再从数组两侧向中间遍历。所以解题思路如下:
- 对给定数组进行升序排序
- 初始化左右指针
- 每次都用一个”最重的“和一个”最轻的“进行配对,如果二人重量小于
Limit
,则此时的”最轻的“上船,即(left++
)。不管”最轻的“是否上船,”最重的“都要上船,即(right--
)并且所需船数量加一,即(num++
)代码如下:
var numRescueBoats = function(people, limit) { people.sort((a, b) => (a - b)); var num = 0 let left = 0 let right = people.length - 1 while (left <= right) { if ((people[left] + people[right]) <= limit) { left++ } right-- num++ } return num };
双指针
class Solution: def maxProfit(self, prices: List[int]) -> int: n = len(prices) if n < 2: return 0 # 必须有两个数字,一买一卖 a, b = 0, 1 # 初始化两个指针 profit = prices[b] - prices[a] for i in range(1, n): if prices[i] - prices[a] < 0: a = i # 卖出去是亏本的 if prices[i] - prices[a] > profit: profit = prices[i] - prices[a]# 卖出能获得最大利润 return profit if profit > 0 else 0 # 最大的 profit 也有可能是负数
当遇到有序数组时,应该优先想到
双指针
来解决问题,因两个指针的同时遍历会减少空间复杂度和时间复杂度。
122. 买卖股票的最佳时机 II
题解:
# 买所有的上涨交易日,下跌的不买 class Solution: def maxProfit(self, prices: List[int]) -> int: profit = 0 for i in range(1, len(prices)): tmp = prices[i] - prices[i-1] # 利润累加 if tmp > 0: profit += tmp #判断是否亏损 return profit
124. 二叉树中的最大路径和
题解:
# 通过root节点的最大路径和 class Solution: def maxPathSum(self, root: TreeNode) -> int: self.maxL = float('-inf') def dfs(root): # 寻找通过root节点的最大路径和 if not root:return 0 # dfs的目的为能提供的最大路径和 leftTree = dfs(root.left) rightTree = dfs(root.right) self.maxL=max(leftTree + rightTree + root.val,self.maxL) return max(0,leftTree+root.val,rightTree+root.val) # 针对递归调用 由需求来决定返回值 dfs(root) return self.maxL