leetcode Two Sum

来源:互联网 发布:国考公务员 知乎 编辑:程序博客网 时间:2024/05/29 17:50

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

my code:

class Solution(object):    def twoSum(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: List[int]        """        mydict = {}        index1 = -1        index2 = -2        if len(nums) < 2:            return [-2, -1]        for i in xrange(len(nums)):            if nums[i] not in mydict.keys():                mydict[nums[i]] = i#这里要注意,如果有重复值的话,这里也就记录最近的一个index            dif = target - nums[i]            if mydict.has_key(dif) :                ind = mydict[dif]                if i > ind:                    index2 = i + 1                    index1 = ind + 1        return index1,index2

other’s code:
http://jelices.blogspot.hk/2014/06/leetcode-two-sum.html

class Solution:    # @return a tuple, (index1, index2)    def twoSum(self, num, target):        processed = {}        for i in range(0, len(num)):            if target-num[i] in processed:                return [processed[target-num[i]]+1,i+1]            processed[num[i]]=i

Note:

we can directly check whether a dict has a key by

if a in mydict:

关于数组的题目 要记得用 hash, sort, binary search(two pointers, or traditional one)

这里还可以使用binary search 的思想,sort之后,使用head pointer i以及tail pointer j,来搜索 two sum 的解空间。two sum!!!!!
http://www.cnblogs.com/springfor/p/3859618.html#3298209

0 0
原创粉丝点击