双指针查找
Q:反转一个单链表
p1作为前面的指针探路,p2作为后面的指针跟进,顺着链表跑一圈,搞定问题。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
p1 = head
p2 = None
while p1 is not None:
temp = p1.next
p1.next = p2
p2 = p1
p1 = temp
return p2
Q:给定一个链表,删除链表的倒数第n个节点,并且返回链表的头结点。
使用两个指针,前面的指针p1先走n步,接着让后面的指针p2与p1同步走,p1走到终点,p2即走到要移除的结点位置。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
p2 = head
p1 = head
while (n > 0):
p1 = p1.next
n -= 1
if (p1 is None): # 移除头结点
return head.next
while (p1.next):
p2 = p2.next
p1 = p1.next
p2.next = p2.next.next
return head
Q:给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head is None:
return head
p1 = head.next
p2 = head
while p1 is not None:
if p1.val == p2.val:
p2.next = p1.next
else:
p2 = p2.next
p1 = p1.next
return head
集合查找
Q:给定两个数组,编写一个函数来计算它们的交集。
直接利用集合这种结构
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
h1 = set(nums1)
h2 = set(nums2)
return list(h1.intersection(h2))
Q:编写一个程序,找到两个单链表相交的起始节点。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> None:
h = set()
temp = headA
while temp is not None:
h.add(temp)
temp = temp.next
temp = headB
while temp is not None:
if temp in h:
return temp
temp = temp.next
return None