문제링크 - https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
해당 문제는 정렬된 numbers 배열에서 두 Index를 가지고 조합을 찾을 수 있다.
앞과 뒤에서 현재 Index 위치의 값들의 합과 target의 값을 비교하여 Index 위치를 옮긴다.
문제에서 입력이 들어오는 데이터는 String s 하나지만 위치 관리를 위해 필요한 변수를 미리 선언해야한다.
startIndex
endIndex
index
현재 numbers의 배열이 오름차순으로 정렬되어 있기 때문에 다음과 같이 투 포인터를 사용할 수 있다.
if(numbers[startIndex]+numbers[endIndex] < target){
startIndex++;
}else if(numbers[startIndex]+numbers[endIndex] > target){
endIndex--;
} else{
result[0] = ++startIndex;
result[1] = ++endIndex;
break;
}
class Solution {
public int[] twoSum(int[] numbers, int target) {
int startIndex = 0;
int endIndex = numbers.length - 1;
int result[] = {0,0};
while(startIndex < endIndex){
if(numbers[startIndex]+numbers[endIndex] < target){
startIndex++;
}else if(numbers[startIndex]+numbers[endIndex] > target){
endIndex--;
} else{
result[0] = ++startIndex;
result[1] = ++endIndex;
break;
}
}
return result;
}
}
시간 복잡도
공간 복잡도
다음과 같은 점수를 기록했다.
더 나은 복잡도를 가지는 방법은 없지만 공간을 아끼기 위해 다음과 같은 방법으로 개선할 수 있었다.