LeetCode12.23

作者: supermanwasd | 来源:发表于2018-12-23 23:01 被阅读0次

    近一年左右没更新,开始刷LeetCode的Python3的题,坚持每天刷一点。我是刷LeetCode国外版本的题(国内外账号记录不是同步),顺便看点英语。

    Two Sum

    今天的题目标题看似很简单,题目描述如下:
    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]

    答案:

    class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        以上是输入框自动给的
        """
        a ={}
        for i, num in enumerate(nums):
            if target-num in a:
                return [a[target - num], i]
            else:
                a[num] = i
    

    这个enumerate()是Python的内置函数,用于一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
    例子:

    seq = ['one', 'two', 'three']
    for i, element in enumerate(seq):
    print(i, seq[i])
    0 one
    1 two
    2 three

    LeetCode反馈如下:
    Runtime: 56 ms, faster than 48.98% of Python3 online submissions for Two Sum.

    相关文章

      网友评论

        本文标题:LeetCode12.23

        本文链接:https://www.haomeiwen.com/subject/rcuokqtx.html