- Date : 2021.06.27(일)
- Time : 25분
- Given an 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.
- Return the indices of the two numbers (1-indexed) as an integer array answer of size 2, where 1 <= answer[0] < answer[1] <= numbers.length.
- The tests are generated such that there is exactly one solution. You may not use the same element twice.
- 2 <= numbers.length <= 3 * 10^4
- -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.
- 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.
def twoSum(self, numbers: list[int], target: int) -> list[int]:
a = 0
b = len(numbers)-1
while a<b:
if numbers[a] + numbers[b] == target:
return [a+1, b+1]
elif numbers[a] + numbers[b] > target:
b = b-1
else :
a = a + 1
: 이 배열을 크기 순으로 정렬이 되어있는 배열이기 때문에 맨 앞과 맨 뒤를 좁혀가면서 더해가며 답을 찾는 방법으로 구현했다. 맨 앞과 맨 뒤를 기준으로 삼은 다음, 더한 값이 target보다 크냐 작냐에 따라 값을 빼주고 더해주고를 반복하였다.