본문 바로가기

LeetCode - Top Interview 150

[Java Script]LeetCode 1. Two Sum

1. 문제 개요

문제 링크 : 1. 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

  • 주어진 값이 배열내의 몇번째 인자끼리의 합으로 만들어진 값인지 구하여라

2. 문제 풀이

간단하게 풀이하면 각각의 요소를 더했을때 결과값이 나오는지 확인하면 되기 때문에 이중 반복문을 활용한 처리를 하였습니다.

 

LeetCode 요구 양식으로 코드 구현

var twoSum = function(nums, target) {
    let i = 0;
    let y = 0;
    let firstNumber = 0;
    let secondNumber = 0;
    while(i < nums.length - 1){
        firstNumber = nums[i];
        y = i + 1;
        while(y < nums.length){
            secondNumber = nums[y]
            if( firstNumber + secondNumber === target) return [i, y]
            y++;
        }
        i++;
    }

 

LeetCode 제출 결과

이렇게 구현에 성공하였습니다.

 

3. 시간 복잡도 계산

splice의 시간복잡도가 O(n)입니다.

더보기

O(2^n) = O(2^n)

 

4. 개선 사항 및 어려웠던 점

단순 값 비교이이게 매우 쉬운 문제였습니다. 투포인트를 활용한 시간 복잡도 개선의 해결법이 존재할것으로 보입니다.

해당 사항으로 개선 작업을 추후 진행 예정입니다.

 

5. 깃허브

관련 사항은 깃허브에 모두 기재되어 있습니다.