leetcode 02. twoSum

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/WUUUSHAO/article/details/88219203

开始的话:
每天三道题,养成良好的思维习惯。
一位爱生活爱技术来自火星的程序汪

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

show the code

class Solution:
    def twoSum(self, nums: list[int], target: int) -> list[int]:
        memory = dict()
        for index, i in enumerate(nums):
            if (target - i) in memory:
                return [memory[target - i], index]
            else:
                memory[i] = index

查看了下第一位同学的代码:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        mirror = {}
        for idx, num in enumerate(nums):
            if num in mirror:
                return [mirror[num], idx]
            mirror[target - num] = idx

需要注意的还是有很多哇!

谢谢

更多代码请移步我的个人github,会不定期更新。
本章代码见code
欢迎关注

猜你喜欢

转载自blog.csdn.net/WUUUSHAO/article/details/88219203