개발이 취미인 주니어 기획자

[투포인터][JavaScript][LeetCode] #167. Two Sum II - Input Array Is Sorted 본문

문제 풀이/알고리즘 문제 풀이

[투포인터][JavaScript][LeetCode] #167. Two Sum II - Input Array Is Sorted

큐 2023. 4. 2. 13:00
728x90
반응형

#투포인터  #MEDIUM

 

Two Sum II - Input Array Is Sorted - LeetCode

Can you solve this real interview question? Two Sum II - Input Array Is Sorted - Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two n

leetcode.com

🌷 문제 설명

✏️ LeetCode 연습문제: Two Sum II - Input Array Is Sorted
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.
Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.
The tests are generated such that there is exactly one solution. You may not use the same element twice.
Your solution must use only constant extra space.


🎃 제한 사항
2 <= numbers.length <= 3 * 10^4
-1000 <= numbers[i] <= 1000
numbers is sorted in non-decreasing order.
-1000 <= target <= 1000
The tests are generated such that there is exactly one solution.

입출력 예

numbers target result
[2, 7, 11, 15] 9 [1, 2]
[2, 3, 4] 6 [1, 3]
[-1, 0]
-1 [1, 2]

 

🌷 내 코드

1. 투포인터

var twoSum = function(numbers, target) {
    let left = 0;
    let right = numbers.length-1;

    while (left < right) {
        let sum = numbers[left] + numbers[right]
        if (sum === target) { 
            return [left+1, right+1]
        } else if (sum < target) { // 만약 합계가 타겟보다 작다면
            left++ // left를 올려줌(숫자 커짐)
        } else { // 합계가 타겟보다 크다면
            right-- // right을 올려줌(숫자 작아짐)
        }
    }
};

 

🌷 코멘트

투포인터 말고 다르게도 풀어보려고 했는데.. 돌아가는 코드가 없었다(시간초과)
투포인터 같은 방향으로 탐색하는것도 해봤는데 아무래도 하나하나 다 따지는 거다보니 시간초과가 났음! 안돌아가는 예제 코드가 있었는데 [-1, -1, -1, ... ] 의 향연에서 1 두개를 찾아서 인덱스 리턴하는 거더라. 엄청 긴 거 보니까 시간초과 왜 났는지 단번에 이해했고요..
이진탐색도 해볼까 해서 해봤는데 시간초과 났다. 어려워 ㅠ

 


블로그 내용에 문제가 있다면 댓글 혹은 아래로 연락주세요!

~대가리 꽃밭인 디지털 노마드가 꿈이예요~

🧚‍♀️ Gyumin Lee

📧 gyumin.q.lee@gmail.com

 

qminlee723 - Overview

noob. qminlee723 has 8 repositories available. Follow their code on GitHub.

github.com

728x90
반응형