LeetCodeアルゴリズム:2つのSum


https://leetcode.com/problems/two-sum/

1. Two Sum


)
Given an array of integers nums and an integer target , return indices of the two numbers such that they add up to target .
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Output: [1,2]
Example 3:
Output: [0,1]```
プール)
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            for j in range(len(nums)):
                if i == j:
                    continue
                if nums[i] + nums[j] == target:
                    num_index = [i, j]
                    return num_index
                
2つの
  • を抽出し、2つの数の和はtargetに等しい.
  • このため、リスト内の2つの異なる数値をダブルfor文で順次比較し、インデックス値をリストに戻すことができます.
  • は2つの異なる数ではない同じ値を加算できないので、iとjの値が同じであれば、continueを通って次のfor文iterに入ります.