알고리즘/LeetCode

LeetCode 167. Two Sum II - Input Array Is Sorted

Timha 2023. 8. 28. 18:04

 

 

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.

 

 

#풀이

 

비교적 간단한 문제라서 금방 풀었다!

 

left와 right 포인터를 둔 후 같다면 값을 리턴시키고 작다면 left포인터 +1 크다면 right 포인터를 -1로 줄이는 방법을 사용했다.

class Solution(object):
    def twoSum(self, numbers, target):

        left = 0
        right = len(numbers)-1
        while True:
            if numbers[left]+numbers[right] == target:
                result = [left+1,right+1]
                break
            elif numbers[left]+numbers[right]> target:
                    right-=1
            elif numbers[left]+numbers[right]< target:
                    left+=1
        return result

 

다른사람의 코드 

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        i = 0
        j = len(numbers) -1
        
        while i<j:
            s = numbers[i] + numbers[j]
            if s == target:
                return [i + 1 , j + 1]
            
            if s > target:
                j-=1
            else:
               i+=1 
        
        return []

다들 비슷하게 투포인터를 사용해서 푼 거 같다