LeetCode——Two Sum

本文介绍了一种解决“两数之和”问题的有效算法。该算法利用哈希表存储已遍历过的数字及其索引,实现了一次遍历即可找到目标数值对应的两个数的索引,时间复杂度为O(n)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

思路

看完题目,第一想到的是分别求出所有可能的组合,显示这种肯定不行
然后想去看看有什么其他规定,比如都是正数,或者是已排序数列,然而发现都没有。
那一对一对的算肯定不行,然后想其他办法,当然最好是遍历一遍就找出来,那么我们通过正向走,向后找是遍历List,那么肯定是n(O),那么我们用一个map把前面的存起来。正向遍历,然后再去map中找互补的数。就是O(n)了。

解法

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        maps = {}
        result = []
        for i in range(len(nums)):
            if maps.has_key(str(nums[i])):
                first = int(maps[str(nums[i])])
                result.append(first)
                result.append(i+1)
                return result
            else:
                num = target-nums[i]
                maps[str(num)] = str(i+1)
        return result
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值