leetcode 1. 两数之和 two sum 解法 python

一.问题描述

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

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, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

 

二.解决思路

先排序,排序之后用两个指针分别指向头和尾,头尾相加如果>target,说明右边的数大了,尾指针向左动一格

主要问题是:

1.排序过程中会丢失原来的位置索引,通过用字典对nums的值和位置做一个映射

2.两个数相同的时候,字典的处理。通过将字典值设为向量来解决,字典和向量的结合要注意一下

更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我

欢迎大家一起讨论一起刷题一起ac

三.源码

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        left=0
        right=len(nums)-1
        num_map={}
        for i in range(0,len(nums)):
            #pay attention to this step, how to deal with the combination of list and dic
            num_map.setdefault(nums[i],[]).append(i)
        nums.sort()
        while left<right:
            if nums[left]+nums[right]>target:
                right-=1
            elif nums[left]+nums[right]<target:
                left+=1
            else :
                if nums[left]==nums[right]:
                    return [num_map[nums[left]][0],num_map[nums[left]][1]]
                else:
                    return [num_map[nums[left]][0],num_map[nums[right]][0]]

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值