leetcode 学习打卡

160-相交链表

题目描述
  • 编写一个程序,找到两个单链表相交的起始节点。
代码(python)
# 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

169-多数元素

题目描述
  • 给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

代码(python)
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        #【不断切分的终止条件】
        if not nums: return None
        if len(nums) == 1: return nums[0]
        #【准备数据,并将大问题拆分为小问题】
        left = self.majorityElement(nums[:len(nums)//2])
        right = self.majorityElement(nums[len(nums)//2:])
        #【处理子问题,得到子结果】
        #【对子结果进行合并 得到最终结果】
        if left == right:
            return left
        if nums.count(left) > nums.count(right):
            return left
        else:
            return right

206-反转链表

题目描述
  • 反转一个单链表。
代码(python)
#迭代
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
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

#递归
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

# 一、
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        def recur(cur,prev):
            if cur==None: return prev #终止条件:如果cur为空,则开始回溯返回prev
            res=recur(cur.next,cur) #递归函数,往后遍历后继节点
            cur.next=prev #修改节点引用指向
            return res #返回res节点
        return recur(head,None)

# 二、
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or head.next == None: return head
        res = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值