leetcode: 1 Two Sum

最近开始刷leetcode, 这是第一题,没什么复杂的直接上代码好了

 
题目是:

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.

这里限制的是每个输入只有1个解,同一个元素不能用两次
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        result = []
        [[result.extend([j, i]) for i in range(len(nums)) if nums[i] + nums[j] == target and i != j and result == []] for j in range(len(nums))]
        return result
算法复杂度n**2
在官网中有一个复杂度为n的算法,如下
class Solution(object):
    def twoSum(self, nums, target):
        if len(nums) <= 1:
            return False
        buff_dict = {}
        for i in range(len(nums)):
            if nums[i] in buff_dict:
                return [buff_dict[nums[i]], i]
            else:
                buff_dict[target - nums[i]] = i
这里,他用了字典来解决该问题,dict[wanted_result] = position,具体思路是重头遍历数组
然后,检查对于某个位置的某个元素是否在一个对应的指定位置存在一个希望的结果存在与字典中,由于有唯一解因此必定存在一个解.
eg:
也就是说是否
1--5
4--2
3--3
5--1
2--4
6--0
这些配对存在

具体步骤如下:
list=[1,4,3,5,2,6], target = 6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
字典dict = {}

询问是否list[0]=1在字典中
否
加入5:0 (第0个要加list[0])
dict[6-list[0]]=dict[5]=0

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
询问是否list[1]=4在字典中
否
加入2:1
dict[6-list[1]]=dict[2]=1

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
询问是否list[2]=3在字典中
否
加入3:2
dict[6-list[2]]=dict[3]=2
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
询问是否list[3]=5在字典中
是dict[5] = 0
返回[dict[5], 3] == [0, 3]

 
 

总结:
在少量数据需要快速计算的情况下,我的方法比较快
在大量数据需要快速计算的情况下,复杂度为n的算法的方法比较快



GitHub: https://github.com/DinnerHowe/LeetCode.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值