← Back to library

Two Sum

配列 nums と整数 target が与えられる。和が target になる 2 要素の添字を返す。

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Constraints:

  • 2nums.length1042 \leq \text{nums.length} \leq 10^4
  • 109nums[i]109-10^9 \leq \text{nums[i]} \leq 10^9
  • 答えはちょうど 1 つ存在する。
使用した概念Hash Table

アプローチ

思考
  • すべての 2 要素の組を試す
  • O(n2)O(n^2) だが実装が単純
実装
class Solution:
    def twoSum(self, nums: list[int], target: int) -> list[int]:
        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]
        return []
Time Space