Leet Code OJ 1. Two Sum [Difficulty: Easy]-Python

题目:

1. 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.

Example:

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

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

第一种解就是暴力求解:复杂度O(n^2)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(0,len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i]+nums[j]==target:
                    return [i,j]

第二种思路就是:由于题目说了有且只有唯一解,可以考虑两遍扫描求解:第一遍扫描原数组,将所有的数重新存放到一个dict中,该dict以原数组中的值为键,原数组中的下标为值;第二遍扫描原数组,对于每个数nums[i]查看target-nums[i]是否在dict中,若在则可得到结果。当然,上面两遍扫描是不必要的,一遍即可,详见代码。O(n)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        keys={}
        for i in range(0,len(nums)):
            if target-nums[i] in keys:
                return [keys[target-nums[i]],i]
            if nums[i] not in keys:
                keys[nums[i]]=i
                

 

一对比就知道速度差距:

Leet Code OJ 1. Two Sum [Difficulty: Easy]-Python_第1张图片

你可能感兴趣的:(算法,leetcode刷题)