카테고리 없음

[LeetCode] 167. Two Sum II - Input Array Is Sorted - Java

jny0 2023. 8. 25. 17:15
 

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

 

문제

더보기

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.

 

Example 1:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].

Example 2:

Input: numbers = [2,3,4], target = 6
Output: [1,3]
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].

Example 3:

Input: numbers = [-1,0], target = -1
Output: [1,2]
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].

 

Constraints:

  • 2 <= numbers.length <= 3 * 104
  • -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.

 

오름차순으로 정렬된 정수 배열과 target 값이 주어진다.

배열의 두 원소의 합이 target 이 되는 경우를 찾고, 그 두 원소의 인덱스를 배열 형식으로 반환하는 문제이다.

 


 

내 풀이

 

class Solution {
    public int[] twoSum(int[] numbers, int target) {

        int[] answer = new int[2];

        int left = 0;
        int right = numbers.length -1;

        while(left < right){
            int sum = numbers[left] + numbers[right];

            if(sum == target){
                answer[0] = left + 1;
                answer[1] = right + 1;
                break;
            }else if(sum > target){
                right--;
            }else{
                left++;
            }
        }

        return answer;
    }
}

투 포인터를 사용해 문제를 해결했다.

이미 오름차순으로 정렬된 배열의 양 끝에 포인터를 하나씩 위치시키고 그 위치에 있는 값들의 합이 target보다 크다면 오른쪽 포인터를 움직이고, 작다면 왼쪽 포인트를 움직인다.

포인터를 움직이면서 target 값과 일치하는 위치에서 정답을 반환한다.

 

  • 시간복잡도 : O(n) - 배열을 한 번만 순회
  • 공간복잡도 : O(1) - 고정된 크기의 정수배열을 사용하므로 추가적인 공간 사용은 O(1)이다.

 

최선의 방법으로 잘 풀이한 것 같다.