两数之和(1)

法一:

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

 

posted on 2020-08-11 14:22  不要挡着我晒太阳  阅读(66)  评论(0编辑  收藏  举报

导航