1. 两数之和

https://leetcode.cn/problems/two-sum/

难度:简单

自己的解法(很慢):

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        result=[]
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i]+nums[j]==target:
                    result.append(i)
                    result.append(j)
        return result

执行用时2357ms,击败5.02%

更好的解法:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # 遍历列表,当前元素nums[i]为两数之和中的一个加数
        for i in range(len(nums)):
            # 计算出需要的另一个加数another
            another = target - nums[i]
            # 遍历列表中的剩余元素,查找another
            if another in nums[i + 1 :]:
                # 如果another存在于列表的剩余元素中,那么当前元素nums[i]和another就是两个加数
                # 用index()方法获取到another在列表剩余元素(也是一个列表,即nums[i+1:])中的索引,还需要加上i+1才是another在nums列表中的索引
                return [i, nums[i + 1 :].index(another) + i + 1]

执行用时311ms,击败36.50%

posted @ 2025-11-12 21:12  YouKong  阅读(4)  评论(0)    收藏  举报