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.

题目大意:给出一个数字列表和一个目标值(target),假设列表中有且仅有两个数相加等于目标值,我们要做的就是找到这两个数,并返回他们的索引值。

例如:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1]

第一反应就是两层循环就可以解决,小case,的确思路简单,但是时间复杂度,你懂得!很简单就能想到的代码如下:
class solution():
    def twoSum(self, nums, target):
        '''
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        '''
        result = []
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i]+nums[j]==target:
                    result.append(i)
                    result.append(j)
                    result.append(target)
                    return result

nums=[20,8,2,15,7]
target=9
print(solution().twoSum(nums,target))

  其实这里也可以用一层循环即可实现,因为我们知道有且仅有一个解;我们可以通过判断target与某一个元素的差值是否也在列表之中即可,这个和两层循环思路类似,但是不难想到计算次数就下降了,代码如下:

class solution():
    def twoSum(self, nums, target):
        '''
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        '''
        result = []
        for i in range(len(nums)):
            first=nums[i]
            seconed=target-first
            if seconed in nums:
                j=nums.index(seconed)
                if i!=j:
                    result.append(i)
                    result.append(j)
                    return result

nums=[20,8,2,15,7]
target=9
print(solution().twoSum(nums,target))

  的确两种方案都轻松通过了,but用时过长,排名老靠后了。之后在网上找到了另一种方案,整体思路和一层循环的方案二有点类似:通过创建字典,将nums里的值和序号对应起来,并创建另一个字典存储目标值(Target)-nums的值,通过判断该值是否在nums内进行判断并返回其对应索引值,代码如下:

class solution():
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        # 创建字典一,存储输入列表的元素值和对应索引
        num_dict = {nums[i]: i for i in range(len(nums))}
        print(num_dict)
        # 创建另一个字典,存储target-列表中的元素的值,小詹称为num_r吧,好表达
        num_dict2 = {i: target - nums[i] for i in range(len(nums))}
        print(num_dict2)
        # 判断num_r是否是输入列表中的元素,如果是返回索引值,不是则往下进行
        result = []
        for i in range(len(nums)):
            j = num_dict.get(num_dict2.get(i))
            if (j is not None) and (j != i):
                result = [i, j]
                break
        return result

nums=[20,8,2,15,7]
target=9
print(solution().twoSum(nums,target))

  该方案,在时间效率上还较为理想


posted @ 2018-07-09 18:44  耐烦不急  阅读(257)  评论(0编辑  收藏  举报