leetcode 160\169\206

本文介绍了三种常见的链表操作:160题的寻找两个单链表的交点,使用双指针法解决;169题的找出数组中的多数元素,通过哈希法和摩尔投票法实现;206题的链表反转,采用迭代和递归两种方式完成。这些算法展示了链表操作的基本技巧和思路。
摘要由CSDN通过智能技术生成

160 相交链表

双指针法

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        pA = headA
        pB = headB
        while headA != headB:
            if headA:
                headA = headA.next
            else:
                headA = pB
            if headB:
                headB = headB.next
            else:
                headB = pA
            # print(headA.val)
            # print(headB.val)
        return headA

169 多数元素

# 哈希法
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        nums_dict = {}
        n = len(nums)
        for i in range(n):
            if nums[i] in nums_dict:
                nums_dict[nums[i]] += 1
            else:
                nums_dict[nums[i]] = 1
        
        for num in nums_dict:
            if nums_dict[num] > n/2: return num
# 摩尔投票法
# 每个不同的数两两抵消,多数的数最后至少还剩下一个
# 初始candidate = nums[0], count = 1, 如果遇到相同的数,则count+1 ,遇到不同的数count - 1, 如果count = 0时,更换候选人
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        n = len(nums)
        candidate = nums[0]
        count = 1
        for i in range(1,n):
            if nums[i] == candidate: count += 1
            else: count -= 1
            if count == 0:
                candidate = nums[i]
                count = 1
        return candidate

206 反转链表

# 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:
        pre = head
        cur = None
        while pre:
            node = pre.next
            pre.next = cur
            cur = pre
            pre = node.next
        return cur

# 递归
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next: return head
        
        res = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值