본문 바로가기
LeetCode

[LeetCode] 1. Two Sum

by JungSeung 2023. 10. 10.
728x90

https://leetcode.com/

 

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 use the same element twice.

You can return the answer in any order.

 

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

 

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

 

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

 

Constraints:

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • Only one valid answer exists.

 

Code :

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    // 배열의 각 요소를 반복합니다.
    for (var i = 0; i < nums.length; i++) {
        // 현재 요소 이후의 요소들과 반복합니다.
        for (var j = i + 1; j < nums.length; j++) {
            // 현재 쌍의 합이 목표값과 같은지 확인합니다.
            if (nums[i] + nums[j] === target) {
                // 그렇다면 두 숫자의 인덱스를 반환합니다.
                return [i, j];
            }
        }
    }
    // 이와 같은 쌍이 없다면 빈 배열을 반환합니다.
    return [];
};

 

Solutions Code :

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    // 숫자와 해당 숫자의 인덱스를 저장하는 Map을 생성합니다.
    const map = new Map();
    // 배열의 각 요소를 반복합니다.
    for (let i = 0; i < nums.length; i++) {
        // 현재 요소에 대한 보수(complement)를 계산합니다.
        const complement = target - nums[i];
        // Map에 보수가 이미 존재하는지 확인합니다.
        if (map.has(complement)) {
            // 보수가 존재한다면, 현재 숫자와 보수의 인덱스를 반환합니다.
            return [map.get(complement), i];
        }
        // 보수가 존재하지 않는다면, 현재 숫자와 해당 숫자의 인덱스를 Map에 저장합니다.
        map.set(nums[i], i);
    }
    // 여기까지 왔다면, 조건을 만족하는 숫자 쌍이 없으므로 빈 배열을 반환합니다.
    return [];
};

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

728x90