首页 > 其他 > 详细

[LeetCode]题1:two sum

时间:2018-07-05 15:26:21      阅读:189      评论:0      收藏:0      [点我收藏+]
 

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

 




[LeetCode]题1:two sum

原文:https://www.cnblogs.com/a-little-v/p/9261180.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!