LeetCode腾讯精选练习50——第十三天

题目160:相交链表
编写一个程序,找到两个单链表相交的起始节点。
题解:

# 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) -> ListNode:
        # a,b = headA, headB
        # while a!=b:
        #     a = a.next if a else headB
        #     b = b.next if b else headA
        # return a 
        d = dict()
        while headA:
            d[headA] = 1
            headA = headA.next
        while headB:
            if headB in d:
                return headB
            headB = headB.next
        return None

运行结果:
在这里插入图片描述
题目169:多数元素
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
题解:

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        nums_set = set(nums)
        for num in nums_set:
            if nums.count(num) > len(nums)/2:
                return num

运行结果:
在这里插入图片描述
题目206:反转链表
反转一个单链表。
题解:

# 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:
        # 迭代
        # res = None
        # while head:
        #     res, res.next, head = head, res, head.next
        # return res
        # 递归
        if head:
            p = head 
            q = head.next  
            while p.next:
                p.next = q.next 
                q.next = head
                head = q
                q = p.next
            return head
        else:
            return head

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44315884/article/details/113094989