はじめに
転職の内定が決まった。
しかし、ある会社でコーディングテストがあったが
全く歯が立たんかった。
克服したいので、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 を入れる
- dictの中にkey=diffのものがあるかをチェック
- 最終的にない: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 };