python leetcode

"""


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,listnums,target):
    for i in listnums:
      for j in listnums:
        if i != j:
          if target == i+j:
            return listnums.index(i),listnums.index(j)
            
 

s = solution()
s.twoSum([1,2,3,4],7)
 
第二种比较好的方式
class Solution(object):
  def twoSum(self, nums, target):
  dic = dict()
  for index,value in enumerate(nums):
    sub = target - value
    if sub in dic:
      return [dic[sub],index]
    else:
      dic[value] = index
 
 
posted @ 2018-07-31 11:08  芒果先生丶  阅读(163)  评论(0编辑  收藏  举报