본문으로 바로가기

LeetCode - Two Sum II - Input Array Is Sorted

category Algorithm/LeetCode 2022. 1. 16. 22:39

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

 

Two Sum II - Input Array Is Sorted - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

/**
 * @param {number[]} numbers
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(numbers, target) {
    let l = 0;
    let r = numbers.length-1;
    while(l<numbers.length-1 && r>0 && l!=r){
        if(numbers[l]+numbers[r]==target){
            return [l+1,r+1]
        }else if(numbers[l]+numbers[r]<target){
            l++;
        }else{
            r--;
        }
    }
};

정렬이 되어있다는 것을 이용한다.

 

1. 양쪽에 l,r이라는 포인터를 둔다.

2. l, r 인덱스에 있는 값을 더했을때 작으면 l++, 크면 r--를 해준다. (정렬이 되어있기 떄문)

'Algorithm > LeetCode' 카테고리의 다른 글

LeetCode - Two Sum  (0) 2022.01.16
LeetCode - Add Two Numbers  (0) 2022.01.16
LeetCode - Triangle  (0) 2022.01.15
LeetCode - Best Time to Buy and Sell Stock II  (0) 2022.01.15
LeetCode - Jump Game II  (0) 2022.01.15