Problem Link: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
Two Sum II - Input Array Is Sorted - LeetCode
Can you solve this real interview question? Two Sum II - Input Array Is Sorted - 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 n
leetcode.com
Two Sum 문제의 변형으로, 이번엔 input array가 오름차순으로 정렬되어 있다.
Solution 1. Brute-force
Time: $O(N^2)$
Space: $O(1)$
Solution 2. Dictionary (hash table)
Time: $O(N)$
Space: $O(N) (Worst)$
Solution 3. Two Pointer
배열이 정렬되어 있는 상황에서 유용하게 사용할 수 있다.
Time: $O(N)$
Space: $O(1)$
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
start = 0
end = len(numbers) - 1
while True:
left, right = numbers[start], numbers[end]
cand = left + right
if cand > target:
end -= 1
elif cand == target:
return [start + 1, end + 1]
else:
start += 1
if start == end:
break # No solutions exist
'Problem Solving' 카테고리의 다른 글
[Leetcode] 226. Invert Binary Tree (0) | 2023.07.13 |
---|---|
[Leetcode] 125. Valid Palindrome (0) | 2023.07.12 |
[Leetcode] 121. Best Time to Buy and Sell Stock (0) | 2023.07.12 |
[Leetcode] 20. Valid Parentheses (0) | 2023.07.11 |
[Leetcode] 1. Two Sum (0) | 2023.07.11 |