1. Two Sum | LeetCode | LeetCode 75

preview_player
Показать описание
1. Two Sum | LeetCode | LeetCode 75

Initialize an empty map: numMap = {}
Iterate through the array:
i = 0, num = 2:
complement = 9 - 2 = 7
numMap doesn't have 7
Add 2 to numMap: numMap = {2: 0}
i = 1, num = 7:
complement = 9 - 7 = 2
numMap has 2 at index 0
Return [0, 1]

Time Complexity
Time Complexity: O(n), where n is the number of elements in the array. We traverse the list at most once.

Space Complexity: O(n), as we store up to n elements in the map.
Рекомендации по теме