본문 바로가기
공부 정리/LeetCode

[LeetCode] Two Sum (Javascript)

by 경적필패. 2021. 12. 13.
반응형

문제

1. Two Sum
Easy

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.

 


문제[번역]

 

정수형 배열 nums 와 정수 target이 주어집니다.

배열안의 두 인덱스의 숫자를 더하세요.(더한 후 target값과 같은지 비교)

한 입력값에 하나의 솔루션만 있다고 가정하시고, 같은 값을 두번 사용할 수 없습니다.

값을 어떤 순서로든 반환 할 수 있습니다.

 

 


 

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]

제약조건

 

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • Only one valid answer exists.

접근방법

단순히 이중포문을 사용하여 같은 인덱스를 가리킬 때는, continue하여 넘겨주고 같은 인덱스를 가르키지 않을 때는, 두 인덱스안의 값을 계산하여 target과 비교해서 target과 같을때 리턴해주었습니다.

 

 

 


코드

 

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    for(let i=0; i<nums.length; i++){
        for(let j=0; j<nums.length; j++){
            if(i == j){
                continue;
            }
            if(nums[i] + nums[j] == target){
                return [i,j];
            }
        }
    }
};

 

 


주의사항

x

 

 

반응형

댓글