[LeetCode]题1:two sum

 

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

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.

 这道题穷举法时间复杂度o(n2)太高了,通过转换为减法利用字典查找数字可以更快的完成。字典初始化和查找可合并成一个循环。另一种想法是对给定数组进行排序,首尾不断相加,直到找到指定的和。

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict={}
        for i , num in enumerate(nums):
            if(target-num)in dict:
                return(dict[target-num],i)
            else:
                dict[num] = i

 




posted @ 2018-07-05 15:14  冰皮抹茶  阅读(114)  评论(0编辑  收藏  举报