LC 1-Two Sum

Goody·2021년 1월 21일
0

알고리즘

목록 보기
7/122

문제

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]
Output: 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]

풀이 방법

  • 배열 내 두 숫자의 덧셈이 target과 같을 때,
    해당 숫자들의 인덱스를 오름차순으로 출력하는 문제이다.
  • 주어진 nums를 이중 for문 으로 돌면서 nums[j]nums[i] 의 합이 target 과 같은지 검사하면 되겠다.

코드

const twoSum = function (nums, target) {
    for(let j = 0; j < nums.length; j++) {
        for(let i = 1; i < nums.length; i++) {
            if( i > j && nums[j] + nums[i] === target) return [j, i];
        }
    }
}

회고

nums의 길이가 10^3 보다 더 길게 주어졌다면 위 방법으로는 풀지 못했을 것 같다. 배열 내 두 원소를 비교하는 알고리즘을 좀 더 알아볼 필요가 있다.

0개의 댓글