본문 바로가기

두두의 알고리즘/문제

[정렬] 릿코드 Easy 167 'Two Sum II - Input Array Is Sorted' (Python)

728x90

<문제 링크>

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

 

Two Sum II - Input Array Is Sorted - LeetCode

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.

leetcode.com


<문제 풀이>

  1. 효율적인 알고리즘을 위해 bisect 라이브러리를 사용
  2. 양수가 포함될 때와 음수(0 포함)만 있을 때 나눠서 코딩

<코드>

from bisect import bisect_right, bisect_left
class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        index = bisect_right(numbers,target)
        answer = []
        for i in range(index):
            if target - numbers[i] in numbers:
                answer.append(i+1)
                answer.append(bisect_right(numbers,target-numbers[i]))
                if len(answer)==2:
                    break
                
        if answer == []:
            index = bisect_left(numbers,target)
            for j in numbers[index:]:
                if target - numbers[j] in numbers:
                    answer.append(j+1+index)
                    answer.append(numbers.index(target-numbers[i])+1+index)
        return answer

 

<고쳐야 할 점>

  • 다양한 케이스 테스트 생각해야 함