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

猜你喜欢

转载自blog.csdn.net/mao_jonah/article/details/80258815