twoSum#

supposed to be surdarla logo

Surdarla

Dec 04 Mon 14:38, 2023

1 min read

문제#

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.

constraints#

  • 2 <= nums.length <= 10^4

  • -10^9 <= nums[i] <= 10^9

think#

\(O(n^2)\)의 이쀑 for 문을 λŒλ©΄μ€ brute force둜 완전탐색을 ν•˜λ©΄μ„œ ν’€ 수 있긴 ν•˜λ‹€. ν•˜μ§€λ§Œ 문제의 μ œν•œμ—μ„œ nums 리슀트의 크기가 맀우 클 수 μžˆλ‹€λŠ” 점과 ν•˜λ‚˜μ˜ μš”μ†Œμ˜ 크기도 맀우 클 수 μžˆλ‹€λŠ” 점이 μ‘΄μž¬ν•˜λŠ” 걸둜 λ΄μ„œλŠ” 쒋은 ν’€μ΄λ‘œλŠ” 보이지 μ•ŠλŠ”λ‹€. O(n)의 μ‹œκ°„λ³΅μž‘λ„λ‘œ μ€„μ΄λŠ” 방법에 λŒ€ν•œ 고민이 ν•„μš”ν•˜λ‹€.

hash map에 λŒ€ν•΄μ„œ 생각해볼 ν•„μš”κ°€ μžˆλŠ” λ¬Έμ œμ΄λ‹€.

python#

import sys, os

problem_num = "twoSum"

path = os.getcwd() + f"\\txt\\{problem_num}" + ".txt"
sys.stdin = open(path, "r")
input = sys.stdin.readline
nums = list(map(int, input().split()))
target = int(input())

from collections import deque
from typing import List


class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        result = []
        popidx = 0
        nums = deque(nums)
        while nums:
            start = nums.popleft()
            popidx += 1
            for idx, i in enumerate(nums):
                if start + i == target:
                    result = [popidx - 1, idx + popidx]
                    break
        return result
answer = Solution().twoSum(nums, target)
answer
[0, 1]

javascript#

Listing 13 nodejs code#
 1/**
 2 * @param {number[]} nums
 3 * @param {number} target
 4 * @return {number[]}
 5 */
 6
 7var twoSum = function (nums, target) {
 8    let popIndex = 0;
 9    while (nums.length > 0) {
10        let start = nums.shift();
11        popIndex++;
12        for (let idx = 0; idx < nums.length; idx++) {
13            if (start + nums[idx] === target) {
14                result = [popIndex - 1, idx + popIndex];
15                break;
16            }
17        }
18    }
19    return result;
20};

Java#

class Solution {
    public int[] twoSum(int[] nums, int target){
        for (int i=0; i< nums.length;i++){
            for (int j = i+1;j<nums.length;j++){
                if (nums[j] == target-nums[i]){
                    return new int[] {i,j};
                }
            }
        }
        return null;
    }
}