LeetCode 分类练习-task04查找

双指针查找

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值