Leetcodeトピック1:2つの数字

タイトル説明

整数配列NUMSと目標値の目標を考えると、配列内の2つの整数の目標値を特定し、その配列の添字に戻るにお願いします。

あなたは、各入力が一つだけ答えに対応することを想定することができます。ただし、同じ配列要素を再使用することはできません。
例:

 给定 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