Leetcode 1 Two Sum

来源:互联网 发布:制作视频字幕软件 编辑:程序博客网 时间:2024/06/05 16:34

1. Two Sum

这个系列的博客是我在leetcode上做题时的一些心得,代码全部使用python。

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(object):    def twoSum(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: List[int]        """        result = {}        for i, num in enumerate(nums):            if target-num in result:                return [result[target-num], i]            else:                result[num] = i
  • 使用python内置函数enumerate同时取出索引和值
  • result是一个辅助字典,key是具体的值,value是索引
  • 计算target-num,看是否在result中存在,若存在则说明target-nums[i]=nums[index]成立,通过字典result找出另一个数字的index,返回index与i
  • 若target-num的值不在字典中,将num作为key保存到字典中,value是num在nums中的索引
原创粉丝点击