算法题

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 Solution1(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        n=len(nums)
        looktable={}
        if n>=2:
            for i,numi in enumerate(nums):
                for j,numj in enumerate(nums[i+1:]):
                    if numj==target-numi:
                        return [i,i+1+j]
        else:
            print 'wrong data'
            return None

  




二 循环一次,同时用一个词典记录访问过的元素
class Solution2(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        n=len(nums)
        looktable={}
        if n>=2:
            for i,numi in enumerate(nums):
                if target-numi in looktable:
                    return [i,looktable[target-numi]]
                looktable[numi]=i
        else:
            print 'wrong data'
            return None

  

nums=[1,2,1,3]
target=2
s=Solution2()
print s.twoSum(nums,target)

返回结果为第一种解决方案返回[0,2]

第二种返回[2,0]

可见第一种方案可以保持结果在原序列中的顺序,第二种方案可以把查找表那部分单独拿出来,这样事先把索引建好,就能保持结果的顺序

class Solution2(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        n=len(nums)
        looktable={}

        if n>=2:
            for i,numi in enumerate(nums):
                looktable[numi]=i
            for i,numi in enumerate(nums):
                if target-numi in looktable:
                    return [i,looktable[target-numi]]
                
        else:
            print 'wrong data'
            return None

  这样初期费时,但是第二次循环时结果会出来很快,因为如果第一个元素满足,则直接返回了。,典型拿空间换时间的策略。



posted @ 2017-09-06 20:35  xqnq2007  阅读(152)  评论(0编辑  收藏  举报