167. 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.
numbers, 특정 두 숫자의 합 target[index1, index2] (index1 < index2)[index1, index2]는 반드시 단 한가지이다.문제 조건 분석
numbers라는 선형 데이터 제공target이 되는 2개의 쌍을 찾는 문제해결 전략
front, behind로 설정numbers의 맨 앞과 맨 뒤로 한다.sum이라고 할 때sum이 target보다 크다면, behind를 이전 값으로 한다.sum이 target보다 작다면, front를 다음 값으로 한다.sum이 target보다 같다면, [front, behind]를 반환한다.class Solution {
public int[] twoSum(int[] numbers, int target) {
int front = 0;
int behind = numbers.length - 1;
while (front < behind) {
int sum = numbers[front] + numbers[behind];
if (sum > target) {
behind--;
} else if (sum < target) {
front++;
} else {
return new int[]{front + 1, behind + 1};
}
}
return new int[0];
}
}

numbers가 딱 하나의 답안을 가진다는 전제를 두기 때문에 해당 분이를 없애 조건문을 조금 덜 사용하도록 했다.class Solution {
public int[] twoSum(int[] numbers, int target) {
int front = 0;
int behind = numbers.length - 1;
int sum = numbers[front] + numbers[behind];
while (sum != target) {
if (sum > target) {
behind--;
} else {
front++;
}
sum = numbers[front] + numbers[behind];
}
return new int[]{front + 1, behind + 1};
}
}

1차 작성한 답안에서는 혹여나 정답이 없는 경우에는 []이 반환되는 분기점이 포함되어 있다.모범 답안에는 해당 분기문이 포함되어 있지 않다.OutOfIndex에러를 내어 프로그램이 중단될 수 있다.