Two Sum | LeetCode(1)

本文针对TwoSum问题进行了深入探讨,提供了基本的实现思路并指出了其中存在的问题——未考虑到数组中可能包含重复元素的情况。此外,文章还提出了如何解决重复数字问题的方法。

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

题目:Two Sum

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

题意:给一个整数数组,找到2个数字使得它们之和等于一个特定目标数。
twoSum函数功能应该返回满足两个数为目标数的索引值,并且index1小于index2.请注意你的返回值是非零的。
假设对于每一个输入只有一个结果。

一段代码

#!/usr/bin/env python
# coding=utf-8
class Solution:
    # @return a tuple, (index1, index2)
    def twoSum(self, num, target):
        map = {}
        j = 1
        for i in num:
            map[i] = j
            j += 1
        for i in num:   
            if map.has_key(target-i) and map[target-i] !=map[i]:
                return min(map[i], map[target - i]), max(map[i], map[target -i])
if __name__ == '__main__':
    s = Solution()
    num = [2, 7 , 11, 15]
    target = 9
    reults = s.twoSum(num, target)  
    print reults
(1, 2)

好像这个代码执行给定的input,也可以得到output,但是 如果是 num=[0, 4, 3, 0] target = 0, 或者 num = [3, 4, 5, 3] target = 6 这样有重复的呢?
显然上面的代码是有问题,那么问题来了,我们怎么解决有重复数字的问题呢?
分析:写代码的时候完全没有考虑重复的情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值