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

2021-07-07 19:18:48 浏览数 (1)

题目:

代码语言:javascript复制
'''
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. 最开始的写法:

代码语言:javascript复制
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

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

2. 利用index改写为:

代码语言:javascript复制
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()来改写:

代码语言:javascript复制
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的,感觉这样很好,借鉴一下。

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


	
0 one
1 two
2 three
>>> 

4. 

代码语言:javascript复制
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 人点赞