LoginSignup
0
0

More than 1 year has passed since last update.

整数配列と整数ターゲットが与えられた場合、2つの数値の合計がターゲットと同値になり、indexを返却する

Posted at

趣向

ターケットの値と配列の中のいずれかの値を足した数が同値の場合のindexを
返却する必要があり、結構悩みました。

nums = [2,7,11,15], target = 9の場合[0,1]
nums = [3,2,4], target = 6の場合[1,2]
nums = [3,3], target = 6の場合[0,1]
nums = [3,0,3], target = 6の場合[0,2]

python3
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        stay = {}
        for index, number in enumerate(nums):
            difference = target - number
            if difference in stay:
                return [stay[difference], index]
            else:
                stay[number] = index

結構悩みましたね^^;
これ以外の実装方法も色々とありそうですが、、これしか浮かびませんでした。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0