Two Sum | LeetCode(1)

来源:互联网 发布:java date时间差 编辑:程序博客网 时间:2024/04/27 02:28

题目:Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

题意:给一个整数数组,找到2个数字使得它们之和等于一个特定目标数。
twoSum函数功能应该返回满足两个数为目标数的索引值,并且index1小于index2.请注意你的返回值是非零的。
假设对于每一个输入只有一个结果。

一段代码

#!/usr/bin/env python# coding=utf-8class Solution:    # @return a tuple, (index1, index2)    def twoSum(self, num, target):        map = {}        j = 1        for i in num:            map[i] = j            j += 1        for i in num:               if map.has_key(target-i) and map[target-i] !=map[i]:                return min(map[i], map[target - i]), max(map[i], map[target -i])if __name__ == '__main__':    s = Solution()    num = [2, 7 , 11, 15]    target = 9    reults = s.twoSum(num, target)      print reults
(1, 2)

好像这个代码执行给定的input,也可以得到output,但是 如果是 num=[0, 4, 3, 0] target = 0, 或者 num = [3, 4, 5, 3] target = 6 这样有重复的呢?
显然上面的代码是有问题,那么问题来了,我们怎么解决有重复数字的问题呢?
分析:写代码的时候完全没有考虑重复的情况。

0 0