1 leetcode-Two Sum

本文提供了一种解决两数之和的经典算法题的方法,包括两种Python实现方案:一种利用字典存储值及其索引来查找配对,另一种通过遍历数组来寻找目标值。这两种方法均可高效找到数组中两个数的索引,使其和为目标值。

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

版本1

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
英文:
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.
中文:
给一个整数数组,返回数组中相加等于target的两个数的索引.
假定每个输入都有符合要求的两个数
举例:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
'''
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if len(nums) < 2:
            return "array error"

        Dict = {} #val->[index]
        for index,val in enumerate(nums):
            if Dict.has_key(val):
                Dict[val].append(index)#重复元素
            else:
                Dict[val] = [index]

        for val in nums:
            if Dict.has_key(target - val):
                if (target - val) == val:
                    if len(Dict[val]) < 2:#只有一个值为val的元素,重复使用,不能返回,第一次写的时候没考虑到,中枪了...
                        continue
                    else:
                        return Dict[val][0:2]
                else:
                    return [Dict[val][0],Dict[target - val][0]]


if __name__ == "__main__":
    s = Solution()
    print s.twoSum([0,3,4,0],0)
    raw_input()

时间复杂度,空间复杂度都为O(n).

版本2,短小精悍…

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if len(nums) < 2:
            return "array error"

        for index,val in enumerate(nums):
            if (target - val) in nums[index + 1:]:
                return [index,index + 1 + nums[index + 1:].index(target - val)]     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值