
[문제]
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.
오름차순으로 정렬된 정수들의 1차원 배열이 주어지면, 목표 숫자에 합해지는 두 개의 숫자를 구하세요. 이 두 숫자를 숫자[index1]와 숫자[index2]라고 합니다. (1 <=index1 <index2 < numbers.length)
정답은 길이 2의 정수형 배열 [index1, index2]로 반환합니다.
문제는 해가 하나만 존재하도록 생성됩니다. 같은 요소를 두 번 사용할 수 없습니다.
class Solution {
public int[] twoSum(int[] numbers, int target) {
int l = 0;
int r = numbers.length - 1;
while (l < numbers.length) {
// 타겟보다 작다면,
if (numbers[l] + numbers[r] < target) {
l++;
} else if (numbers[l] + numbers[r] > target) { // 타겟보다 크다면
r--;
} else { // 같다면 정답
return new int[] {l + 1, r + 1};
}
}
return null;
}
}