[LeetCode] 1. Two Sum

两数之和算法解析
本文介绍了一种解决“两数之和”问题的有效算法。该算法通过使用哈希表来存储数组元素及其对应的索引,实现了在一次遍历中找到目标和的两个数。这种方法不仅简化了问题的复杂度,还提高了查找效率。
__author__ = 'zenglinwang'

class Solution(object):

    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """

        map = dict()

        # Since two numbers are mutually complemented, one pass hash table can do.
        for i in range(0, len(nums)):
            complement = target - nums[i]
            # print "- [{0:d},{1:d}]".format(nums[i], i)
            # print map.items()
            if complement in map.keys() and map.get(complement) != i:
                # print "[{0:d},{1:d}]".format(map.get(complement), i)
                return [map.get(complement), i]
            map[nums[i]] = i

# s = Solution()
# s.twoSum([0,4,3,4,5,4], 8)

 

转载于:https://www.cnblogs.com/skyssky/p/5740405.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值