python LeetCode 题库 (不定时更新)

这篇博客主要探讨了如何使用Python解决LeetCode中的两道经典问题:1. 找出数组中的众数,即出现次数超过数组长度一半的元素;2. 在数组中找到两个数,使它们的和等于给定的目标值。通过示例代码解析了解题思路和方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. (简单)给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
    你可以假设数组是非空的,并且给定的数组总是存在众数。
    示例 1:
    输入: [3,2,3]
    输出: 3
    示例 2:

输入: [2,2,1,1,1,2,2]
输出: 2

answer:

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l = set(nums)
        ma = 0
        for i in l:
            x = nums.count(i)
            if x > ma:
                ma = x
                re = i
        return re
  1. (简单)给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

answer

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        m = len(nums)
        for i in range(m):
            t = target - nums[i]
            for j in range(m):
                if i != j and t == nums[j]:
                    return i,j

3.(中等)给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
answer

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

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """

        dummy_head = ListNode(-1)
        cur = dummy_head
        
        carry = 0
        
        while l1 is not None and l2 is not None:
            val = l1.val + l2.val + carry
            cur.next = ListNode(val % 10)
            cur = cur.next
            carry = val // 10
            l1 = l1.next
            l2 = l2.next
            
        while l1 is not None:
            val = l1.val + carry
            cur.next = ListNode(val % 10)
            cur = cur.next
            carry = val // 10
            l1 = l1.next
            
        while l2 is not None:
            val = l2.val + carry
            cur.next = ListNode(val % 10)
            cur = cur.next
            carry = val // 10
            l2 = l2.next
        
        if carry == 1:
            cur.next = ListNode(1)
            
        return dummy_head.next
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值