[LeetCode]题1:two sum

Posted 冰皮抹茶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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

 







以上是关于[LeetCode]题1:two sum的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 第 371 题 (Sum of Two Integers)

1_Two Sum --LeetCode

[LeetCode] 1 Two Sum

[LeetCode] 1 Two Sum

leetcode算法题笔记|two sum

LeetCode 1 - Two Sum