2.two_sum

Two Sum

hint: x = target - y
hint: use hash map

Objects vs. Maps

helper func:

  • map.get(key) = value
  • Using map[key] will return undefined. It different from an object.
  • map.has(key) = boolean

|
|
|
|
|
|
|
|
|

1
2
3
4
5
6
7
8
9
10
11
function twoSum(nums: number[], target: number): number[] {
let hash = new Map;
for (let i = 0; i < nums.length; i++) {
const secondNum: number = target - nums[i];
if (hash.has(secondNum)) {
return [hash.get(secondNum), i];
}
hash.set(nums[i], i);
}

};