1.Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
CODE:
class Solution(object):
def twoSum(self, nums, target):
num_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i
OUTPUT:
[2,7,11,15]
9
[0,1]
2.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 numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.
CODE:
`class Solution:
def twoSum(self, numbers, target):
start = 0
end = len(numbers) - 1
while start < end:
total = numbers[start] + numbers[end]
if total == target:
return [start + 1, end + 1]
elif total < target:
start += 1
else:
end -= 1
return [-1, -1]`
OUTPUT:
[2,7,11,15]
9
[1,2]
Top comments (0)