[LeetCode]easy - Two Sum - python

Problem Description:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

题目要求输出相加值为给定target的两个元素在List中的下标。

思路一:

两重循环,遍历给定List中两两相加的每一种结果,如和target数目相同则输出下标。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        rtype = []
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if nums[i] + nums[j] == target:
                    rtype.append(i)
                    rtype.append(j)
        return rtype

但这样做会导致时间复杂度太大。

思路二:

换个思路,因target给定,那么对于一次遍历中需要寻找的就是target - 当前数的数值是否出现在这个List中。

则可以用一个空字典存放遍历过的元素,字典中的键对应的是原列表中的数值,字典中的值对应原列表中的下标。

每次我们都判断一下列表中的元素的“target - 元素值”是否在字典中。如果在,只需返回这两个元素的下表即可;如果不在,就把该元素加入到字典中,供后面的元素对比。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        rtype = {}
        for i in range(len(nums)):
            if target - nums[i] in rtype:
                return [rtype[target - nums[i]], i]
            if nums[i] not in rtype:
                rtype[nums[i]] = i

时间复杂度大大降低。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值