LeetCode: 1. Two Sum python

来源:互联网 发布:特斯拉潜能软件下载 编辑:程序博客网 时间:2024/05/18 00:17

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
看题目的意思,只要找出两个数相加等于target就行了。

再看提示有哈希,那就用哈希吧,在python中,哈希就是个字典。试了一下,我用nums的值当key,target-nums[i]的值当value,下面贴代码

  1. class Solution(object):
  2.     def twoSum(self, nums, target):
  3.         """
  4.         :type nums: List[int]
  5.         :type target: int
  6.         :rtype: List[int]
  7.         """
  8.         mDict = {}
  9.         for i in range(len(nums)):
  10.             if mDict.has_key(nums[i]):
  11.                 return [nums.index(mDict[nums[i]]),i]
  12.             else:
  13.                 mDict[target - nums[i]] = nums[i]
  14.         del mDict
  • 其实很简单,大家可以看着代码体会一下,文字不是很好表达。





0 0
原创粉丝点击