[Leetcode]167. Two Sum II - Input Array Is Sorted

2024. 7. 31. 23:53Algorithm

1. problem : 

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

 

2. solution 1 :

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        hashMap = {}
        for i in range(len(numbers)):
            diff = target - numbers[i] 
            if diff in hashMap.keys():
                return [hashMap[diff],i+1] 
            hashMap[numbers[i]] = i+1

hashMap을 이용한 풀이다. diff가 있으면 반환, 없으면 numbers [i] 추가 

 

3. solution 2 :

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

two pointer를 이용한 기법. sorting이 되었기 때문에 이용가능. 

'Algorithm' 카테고리의 다른 글

[Leetcode]20. Valid Parentheses  (0) 2024.08.01
[Leetcode]42. Trapping Rain Water(x)  (0) 2024.08.01
[Leetcode]125. Valid Palindrome  (0) 2024.07.31
[Leetcode]128. Longest Consecutive Sequence  (0) 2024.07.31
[Leetcode]36. Valid Sudoku(x)  (0) 2024.07.31