82. Remove Duplicates from Sorted List II
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = pre = ListNode(111)
dummy.next = head
while head and head.next:
if head.val == head.next.val:
while head and head.next and head.val == head.next.val:
head = head.next
head = head.next
pre.next = head
else:
pre = pre.next
head = head.next
return dummy.next
369. Plus One Linked List
p1指向最后面非9的数字。p2指向结尾。
class Solution(object):
def plusOne(self, head):
# two pointers
dummy = ListNode(0)
dummy.next = head
p1 = p2 = dummy
while p2.next:
p2 = p2.next
if p2.val != 9:
p1 = p2
if p2.val != 9:
p2.val += 1
else:
p1.val += 1
while p1.next:
p1.next.val = 0
p1 = p1.next
if dummy.val != 0:
return dummy
else:
return dummy.next
109. Convert Sorted List to Binary Search Tree
class Solution(object):
def sortedListToBST(self, head):
def helper(first, tail):
# if not first: return None # 注意,这里是错误的
if first == tail: return None
fast = slow = first
while fast != tail and fast.next != tail:
slow = slow.next
fast = fast.next.next
root = TreeNode(slow.val)
root.left = helper(first, slow)
root.right = helper(slow.next, tail)
return root
return helper(head, None)
986. Interval List Intersections
class Solution(object):
def intervalIntersection(self, A, B):
i = j = 0
res = []
while i < len(A) and j < len(B):
# 没有overlap
if A[i].start > B[j].end:
j += 1
elif B[j].start > A[i].end:
i += 1
else: # overlap
res.append(Interval(max(A[i].start, B[j].start), min(A[i].end, B[j].end)))
if A[i].end < B[j].end:
i += 1
else:
j += 1
return res
445. Add Two Numbers II
用堆栈做
class Solution(object):
def addTwoNumbers(self, l1, l2):
stack1, stack2 = [], []
while l1:
stack1.append(l1.val)
l1 = l1.next
while l2:
stack2.append(l2.val)
l2 = l2.next