法一:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        ret = []
        for i in range(len(nums)):
            for j in range(1,len(nums)-i):
                if nums[i] + nums[-j] == target:
                    ret.append(i)
                    ret.append(len(nums)-j)
                    return re

法二:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
    
         hashmap = {}
        for ind, num in enumerate(nums):
            hashmap[num] = ind
        for i, num in enumerate(nums):
            j = hashmap.get(target - num)
            if j is not None and i != j:
                return [i, j]
法三:
class Solution(object):
    def twoSum(self, nums, target):
        ret = []
        for i in nums:
            other = target-i
            current_index = nums.index(i)
            if other in nums[current_index+1:]:
                other_index = nums[current_index+1:].index(other)
                ret.append(current_index)
                ret.append(current_index+other_index+1)
                break
        return ret

 

相关文章:

  • 2021-05-12
  • 2021-10-21
  • 2021-11-25
  • 2021-11-04
  • 2021-06-20
  • 2022-01-23
猜你喜欢
  • 2021-11-25
  • 2021-11-21
  • 2022-02-09
相关资源
相似解决方案