Two Sum - 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. Sliding Window
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
index_list = [i for i in range(len(nums))]
new_nums = list(map(lambda x, y: (x, y), nums, index_list))
new_nums.sort()
start, end = 0, len(new_nums) - 1
while start < end:
temp = new_nums[start][0] + new_nums[end][0]
if temp < target:
start += 1
elif temp == target:
return [new_nums[start][1], new_nums[end][1]]
elif temp > target:
end -= 1

너무나 유명한 문제여서 설명은 이하 생략.
개인적으로 요즘 코딩 테스트에 자주 등장하는 알고리즘 기법인 것 같다.
'Algorithm' 카테고리의 다른 글
| 739. Daily Temperatures (0) | 2021.05.06 |
|---|---|
| 78. Subsets (2) | 2021.05.06 |
| 206. Reverse Linked List (0) | 2021.05.05 |
| 234. Palindrome Linked List (0) | 2021.05.04 |
| 226. Invert Binary Tree (1) | 2021.05.03 |