Commit 9ba9948d by 杨鹏

寒假作业

parent 0362ab2d
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if (root == None):
return None
if ((root.val >= p.val and root.val <= q.val) or (root.val >= q.val and root.val <= p.val)):
return root
if (root.val < p.val and root.val < q.val):
return self.lowestCommonAncestor(root.right, p, q)
if (root.val > p.val and root.val > q.val):
return self.lowestCommonAncestor(root.left, p, q)
return None
def lowestCommonAncestor1(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
son_dic = {}
def get_son_dic(root):
if not root:
return []
else:
son_dic[root] = [root] + get_son_dic(root.left) + get_son_dic(root.right)
return son_dic[root]
result = root
while True:
if p in son_dic[result.left] and q in son_dic[result.left]:
result = result.left
elif p in son_dic[result.right] and q in son_dic[result.right]:
result = result.right
else:
return result
# 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
# 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。注意你不能在买入股票前卖出股票。
# 示例 1:输入: [7,1,5,3,6,4]输出: 5解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
# 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
# 示例 2:输入: [7,6,4,3,1]输出: 0解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
# 列表个数
l = len(prices)
# 如果列表个数只有1个,那就不用比了
if(l < 2):
return 0
# 设置初始最小价和最大利润
min_price = prices[0]
max_Profit = 0
for i in prices:
min_price = min(min_price, i)
max_Profit = max(max_Profit, i - min_price)
return max_Profit
# 将两个有序链表合并为一个新的有序链表并返回。
# 新链表是通过拼接给定的两个链表的所有节点组成的。
# 示例:输入:1->2->4, 1->3->4输出:1->1->2->3->4->4
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 递归法
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 == None and l2 == None:
return None
if l1==None:
return l2
if l2==None:
return l1
if l1.val<=l2.val:
l1.next=self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next=self.mergeTwoLists(l1,l2.next)
return l2
# def mergeTwoLists2(self, l1, l2):
# """
# :type l1: ListNode
# :type l2: ListNode
# :rtype: ListNode
# """
# head = ListNode(0)
# first = head
# while l1 != None and l2 != None:
# if l1.val <= l2.val:
# head.next = l1
# l1 = l1.next
# else:
# head.next = l2
# l2 = l2.next
# head = head.next
# if l1 != None:
# head.next = l1
# elif l2 != None:
# head.next = l2
# return first.next
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment