Leetcode - 167. Two Sum II - Input array is sorted

문제

Loading...
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

풀이

브루트 포스

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        for idx1, num1 in enumerate(numbers):
            for idx2, num2 in enumerate(numbers[idx1 + 1 :]):
                if num1 + num2 > target:
                    break
                if num1 + num2 == target:
                    return sorted([idx1 + 1, idx1 + idx2 + 2])

Binary search

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        for idx, num in enumerate(numbers):
            new_target = target - num

            left, right = idx + 1, len(numbers) - 1
            while left <= right:
                mid = (left + right) // 2

                if numbers[mid] < new_target:
                    left = mid + 1
                elif numbers[mid] > new_target:
                    right = mid - 1
                else:
                    return [idx + 1, mid + 1]

Two pointers

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        left, right = 0, len(numbers) - 1
        while left != right:
            if numbers[left] + numbers[right] < target:
                left += 1
            elif numbers[left] + numbers[right] > target:
                right -= 1
            else:
                return [left + 1, right + 1]