Algocode: add two_sums solution

This commit is contained in:
t0xa 2026-01-19 20:09:28 +03:00
parent 22abae2fd6
commit 33798cf043
2 changed files with 120 additions and 0 deletions

View file

View file

@ -0,0 +1,120 @@
"""
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
"""
"""
Допустим у нас будет хэшмапа, где будет лежать следующая пара ключ-значение:
{
<сколькое_хватает_доели> : <list_position>
}
Пробуем пройтись по очереди на первом примере
0. delta = {}
1. nums[0] = 2
delta = {
7:0
}
2. nums[1] = 7
2.1 Проверяем, есть ли в delta ключ `0`?
2.2 Да - получается наш ответ : [0,1]
---
Example 2
Input: nums = [3,2,4], target = 6
0. delta = {}
1. nums[0] = 3
sub = target - 3 = 3
delta = {
3:0
}
2. nums[1] = 2
2.0 index = 1
2.1 Есть ли в delta ключ 2? -> нет, следовательно:
2.2 sub = target - 2 = 4
delta = {
3:0
4:1
}
3. nums[2] = 4
3.0 index = 2
3.1 Есть ли в delta ключ 4? -> Есть
3.2 Возвращаем [delta[4], index]
"""
class Solution:
def twoSum(self, nums, target: int):
if len(nums) == 2:
return [0,1]
delta = dict()
for index, element in enumerate(nums):
if index == 0:
delta[target - element] = index
continue
res = delta.get(element)
if isinstance(res, int):
return [index, res]
sub = target - element
delta[sub] = index
raise ValueError("Cannot find valid answer")
s = Solution()
nums = [2,7,11,15]
target = 9
# Output: [0,1]
"""
1
delta = {
7:0
}
2
"""
assert s.twoSum(nums, target) in [[0,1], [1,0]], f"result = {s.twoSum(nums,target)}"
nums = [3,2,4]
target = 6
# Output: [1,2]
assert s.twoSum(nums, target) in [[1,2], [2,1]]
nums = [3,3]
target = 6
# Output: [0,1]
assert s.twoSum(nums, target) in [[0,1], [1,0]]