Leetcode 001: 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.

例子:

 [2,7,11,15], 9  输出 [0, 1]

思路:

  主要考虑:

    1、是否有重复得如 [3,2,4] 6 得情况,不要输出[0, 0] ,题目中说明:you may not use the same element twice.

    2、考虑不同方法主要有三种:暴力,两遍哈希表和一遍哈希表。

下面给出我的实现:

   两遍哈希表:

#coding:utf-8

'''
    leetcode 001 question
    author: xuyaowen time: 2018-04-02 
    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.
'''
class Solution(object):
    def twoSum(self, nums, target):
        pair = dict(zip(nums,range(len(nums))))
        for i in range(len(nums)):
            p =  target - nums[i]
            if  p in nums:
                if p == target/2 and pair[p] == i:
                    continue
                return [i, pair[p]] #所有的解对应当下的坐标
# 1319 ms 时间效率很慢
# 解决方法,两遍哈希表
ans =  Solution()
print(ans.twoSum([3, 3], 6))

  一遍哈希表:

#coding:utf-8

'''
    leetcode 001 question
    author: xuyaowen time: 2018-04-02 
    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.
'''
class Solution(object):
    def twoSum(self, nums, target):
        seen = {}
        for i, n in enumerate(nums):
            o = target-n
            if o in seen:
                return [seen[o], i]
            seen[n] = i
# 40ms
# 一遍哈希表
ans =  Solution()
print(ans.twoSum([2, 7, 11, 15], 9))

  暴力算法就不展示了。

     更多得代码请参见: https://github.com/yaowenxu/Leetcode

  转载请注明出处

原文地址:https://www.cnblogs.com/xuyaowen/p/leetcode-001.html