Leetcode 주제 1 : 두 숫자

제목 설명

정수 배열 nums 및 목표 값 목표를 감안하고, 배열의 두 정수의 목표 값을 식별하고 그 배열 첨자로 돌아 부탁드립니다.

각 입력이 하나의 답에 해당하는 것으로 가정 할 수있다. 그러나 같은 배열 요소를 다시 사용할 수 없습니다.
예 :

 给定 nums = [2, 7, 11, 15], target = 9
 因为 nums[0] + nums[1] = 2 + 7 = 9
 所以返回 [0, 1]

해결

(1)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashmap = {}
        for index, num in enumerate(nums):
            another_num = target - num
            if another_num in hashmap:
                return [hashmap[another_num], index]
            hashmap[num] = index
        return None

(2)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for index_a, a in enumerate(nums):
            for index_b, b in enumerate(nums):
                ans = []
                if index_a == index_b:
                   continue
                if a + b == target:
                    ans.append(index_a)
                    ans.append(index_b)
                    return ans
                else: 
                    continue
게시 33 개 원래 기사 · 원의 찬양 3 · 조회수 5541

추천

출처blog.csdn.net/weixin_42990464/article/details/104544646