카테고리 없음

leetcode 0002 - Add Two Numbers / Medium / Typescript

eumjo_o 2023. 3. 9. 17:20

https://leetcode.com/problems/two-sum/

 

Two Sum - LeetCode

Can you solve this real interview question? Two Sum - Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not

leetcode.com

 

  • Map을 사용해 nums 배열 순회
    • 찾으려는 값을 key로 사용하고, index에 해당하는 값이 value가 되도록 하여 map에 저장하면서 배열을 순회
  • O(n)의 time complexity
function twoSum(nums: number[], target: number): number[] {
  const map: { [num: number]: number } = {};

  for (let index = 0; index < nums.length; index += 1) {
    const num = nums[index];
    const num2 = target - num;
    const index2 = map[num2];

    if (index2 !== undefined) {
      return [index, index2];
    } else {
      map[num] = index;
    }
  }

  return [];
}