Python学习:关于Two Sum问题的一些记录

题目:

'''
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.'''

1. 最开始的写法:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if len(nums) <1 :
            return false
        for i in range(len(nums)):
            temp=target-nums[i]
            if temp in nums.index
            while j<len(nums):
                sum=nums[i]+nums[j]
                if sum==target:
                    return i,j
                else:
                    j+=1
      

大部分例子都能通过,有一个出现了如下图所示的提示:

2. 利用index改写为:

class Solution:
    def twoSum(self, nums, target):       
        if len(nums) <1 :
            return false
        for i in range(len(nums)):
            temp=target-nums[i]
            if temp in nums:
                if i!=nums.index(temp):
                    return i,nums.index(temp)

3. 利用enumerate()来改写:

class Solution:
def twoSum(self, num, target):
    d = dict()
    for index, number in enumerate(num):
        try:
            return ((d[target-number]+1, index+1))
        except:
            d[number] = index

看到有加了try的,感觉这样很好,借鉴一下。

enumerate(sequence, [start=0])

  • sequence,序列或迭代对象等
  • start 下标起始位置
  • 返回值:返回枚举对象,
>>> sq=['one','two','three']
>>> for index,element in enumerate(sq):
	print(index,sq[index])


	
0 one
1 two
2 three
>>> 

4. 

class Solution:
    # @return a tuple, (index1, index2)
    # 8:42
    def twoSum(self, num, target):
        map = {}
        for i in range(len(num)):
            if num[i] not in map:
                map[target - num[i]] = i + 1
            else:
                return map[num[i]], i + 1

        return -1, -1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

烤粽子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值