第八章 贪心(一)
主要内容
- 贪心
- 链表
贪心题目
122. 买卖股票的最佳时机 II
思路分析
假如第0天买入,第3天卖出,那么利润为:prices[3] - prices[0]。
相当于(prices[3] - prices[2]) + (prices[2] - prices[1]) + (prices[1] - prices[0])。
局部最优:收集每天的正利润,全局最优:求得最大利润。
代码
class Solution:
def maxProfit(self, prices: List[int]) -> int:
res = 0
for i in range(1, len(prices)):
res += max(prices[i] - prices[i-1], 0)
return res
55. 跳跃游戏
思路分析
维护一个最远可达距离
代码
class Solution:
def canJump(self, nums: List[int]) -> bool:
n = len(nums)
# 维护一个最远可达距离
distance = 0
for i in range(n):
if i <= distance:
distance = max(distance, i + nums[i])
if distance >= n-1:
return True
else:
return False
return False
45. 跳跃游戏 II
思路分析
如果当前覆盖最远距离下标不是是集合终点,步数就加一,还需要继续走。
如果当前覆盖最远距离下标就是是集合终点,步数不用加一,因为不能再往后走了。
代码
class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
step = 0
curdistance = 0
nextdistance = 0
for i in range(n):
nextdistance = max(nextdistance, i + nums[i])
if i == curdistance:
# curdistance 还未覆盖终点
if curdistance < n-1:
# 需要走下一步
step += 1
curdistance = nextdistance
# 下一步覆盖终点
if nextdistance >= n-1:
break
# curdistance 已是终点
else:
break
return step
链表题目
203.移除链表元素
思路分析
代码
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummy = ListNode(-1)
dummy.next = head
p = dummy
while p and p.next:
if p.next.val == val:
p.next = p.next.next
else:
p = p.next
return dummy.next
707.设计链表
思路分析
代码
class ListNode:
def __init__(self,val,next = None):
self.val = val
self.next = next
class MyLinkedList:
def __init__(self):
self.dummy = ListNode(-1)
self.size = 0
def get(self, index: int) -> int:
if index < 0 or index >= self.size:
return -1
cur = self.dummy
for _ in range(index + 1):
cur = cur.next
return cur.val
def addAtHead(self, val: int) -> None:
self.addAtIndex(0, val)
def addAtTail(self, val: int) -> None:
self.addAtIndex(self.size,val)
def addAtIndex(self, index: int, val: int) -> None:
if index > self.size:
return
index = max(0, index)
pre = self.dummy
for _ in range(index):
pre = pre.next
newNode = ListNode(val)
newNode.next = pre.next
pre.next = newNode
self.size += 1
def deleteAtIndex(self, index: int) -> None:
if 0 <= index < self.size:
pre = self.dummy
for _ in range(index):
pre = pre.next
pre.next = pre.next.next
self.size -= 1
206.反转链表
思路分析
代码
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None or head.next is None:
return head
newhead = self.reverseList(head.next)
head.next.next = head
head.next = None
return newhead