21/100. Two Sum

在这里插入图片描述
给定一个数组和target,求数组中相加的和为target的index,返回一个list。

思路一:
将数组nums排序,然后设定两个指针,一个指针的index为0,往后走;一个指针的index为len(nums)-1,往前走。
若相加数值等于target,满足(返回“nums.index(value)”);
若相加数值小于target,前指针往后走;
若相加数值大于target,后指针往前走。

注意:若两个数的值相等,则需考虑切片找出第2个数的位置,因为index()方法只能list中找到第一个匹配的值。

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if not nums:
            return None
            
        n = sorted(nums)  # 复杂度:n*logn
        
        i = 0
        j = len(n)-1
        plus = 0
        res = []
        
        while i<len(n) and j>=0:
            plus = n[i]+n[j]
            if plus == target:
                res.append(nums.index(n[i]))
                if n[i]==n[j]:  #两个同样的值
                    res.append(nums[res[0]+1:].index(n[j])+(res[0]+1))  #别忘了加被切掉的那部分
                else:
                    res.append(nums.index(n[j]))
                return res
            elif plus > target:
                j -= 1
            elif plus < target:
                i += 1
        return None

思路二:
使用dict,若i=0,nums[i]=2:
则dict中,key=target-nums[i]=9-2=7,value=i=0,意思即为缺7,则i=0的位置可以满足条件。

class Solution:
    def twoSum(self, nums, target):
        if len(nums) <= 1:
            return False
        buff_dict = {}
        for i in range(len(nums)):
            if nums[i] in buff_dict: #索引key,非value
                return [buff_dict[nums[i]], i]
            else:
                buff_dict[target-nums[i]] = i
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值