주어진 array에서 합이 target이 되는 요소의 인덱스를 찾아야한다. 👉 hash table
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashTable = {}
for idx, num in enumerate(nums):
diff = target - num
if diff in hashTable:
return [idx, hashTable[diff]]
hashTable[num] = idx
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
const map = new Map();
for (const [idx, num] of nums.entries()) {
const diff = target - num;
if (map.has(diff)) return [idx, map.get(diff)];
else map.set(num, idx);
};
}