1.leetcode 两数之和(简单)

    技术2024-12-24  14

    leetcode python 刷题记录,从易到难


    一、题目


    二、解答

    A、version1

    1.思路

    把数组的元素放到字典里(key为数值,value为索引),遍历key,看是否包含值等于(target减当前key)的元素,如果有,则把这两个元素的索引添加到新数组,然后返回

    2.实现
    class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dict1 = {} result = [] for index,num in enumerate(nums): dict1[num] = index for key in dict1: if dict1.__contains__(target-key): result.append(dict1.get(key)) result.append(dict1.get(target-key)) return result
    3.提交结果

    4.反思

    没有考虑两数相等的情况


    B、version2

    1.修改思路

    把数组的元素放到字典里(key为数值,value为索引),遍历key,看是否包含值等于(target减当前key)的元素,如果有判断索引是否相等,如果不等则把这两个元素的索引添加到新数组,然后返回

    2.实现
    class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dict1 = {} result = [] for index,num in enumerate(nums): dict1[num] = index for key in dict1: if dict1.__contains__(target-key) and dict1.get(key) != dict1.get(target-key): result.append(dict1.get(key)) result.append(dict1.get(target-key)) return result
    3.提交结果

    4.反思

    忽略了python dict无法添加重复值的特点,导致重复元素只能添加1个到字典中


    C、version3(最终版本)

    1.修改思路

    把数组的元素放到字典里(key为数值,value为索引),在放入时就判断是否包含值等于(target减当前key)的元素,如果包含值等于(target减当前key)的元素,把这两个元素的索引添加到新数组,然后返回

    2.实现
    class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dict1 = {} for index,num in enumerate(nums): if dict1.__contains__(target-num): return [dict1.get(target-num),index] dict1[num] = index
    3.提交结果

    三、Github地址:

    https://github.com/m769963249/leetcode_python_solution/blob/master/easy/1.py

    参考链接:

    leetcode官网

    Processed: 0.009, SQL: 9