0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Two Sum_NeetCode

Last updated at Posted at 2025-07-30

はじめに

転職の内定が決まった。
しかし、ある会社でコーディングテストがあったが
全く歯が立たんかった。
克服したいので、NeetCodeを少しずつ進めていく。
ひとまずEasyのものから。
その際の回答に必要だった知識や気づきを書いていこうと思う。

挑戦した問題

問題の概要

Given an array of integers nums and an integer target, return the indices i and j such that nums[i] + nums[j] == target and i != j.

You may assume that every input has exactly one pair of indices i and j that satisfy the condition.

Return the answer with the smaller index first.

Example

Input: 
nums = [3,4,5,6], target = 7

Output: [0,1]

回答の流れ

  • 空Dictを作る key:num value:numにおけるindex 3,0 4,1
  • numsをforeach回す
  • diff=targetとnumの差を定義する
    • dictの中にkey=diffのものがあるかをチェック
      • ある:Keyとnumを返す
      • ない:Dictに key:num value:numにおけるindex を入れる
  • 最終的にない:null

回答のために必要だった知識

// Key=int,value=intの辞書を作る
Dictionary<int,int> keyValuePairs = new Dictionary<int,int>();
// Dict(Key)の場合はContainsKeyを使っている
if (keyValuePairs.ContainsKey(diff))
// 配列を返す時、 {}なのね
return new int[] { keyValuePairs[diff],i };

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?