Skip to content

Commit 86d5189

Browse files
committed
Two Sum II - Input array is sorted
1 parent 064df49 commit 86d5189

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Two_Sum_II_Input_array_is_sorted.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Given an array of integers that is already sorted in ascending order,
2+
# find two numbers such that they add up to a specific target number.
3+
#
4+
# The function twoSum should return indices of the two numbers such
5+
# that they add up to the target, where index1 must be less than index2.
6+
#
7+
# Note:
8+
#
9+
# Your returned answers (both index1 and index2) are not zero-based.
10+
# You may assume that each input would have exactly one solution and
11+
# you may not use the same element twice.
12+
# Example:
13+
#
14+
# Input: numbers = [2,7,11,15], target = 9
15+
# Output: [1,2]
16+
# Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
17+
18+
19+
class Solution:
20+
def twoSum(self, numbers, target):
21+
22+
left = 0
23+
right = len(numbers) - 1
24+
25+
while left < right:
26+
total = numbers[left] + numbers[right]
27+
28+
if total == target:
29+
return [left + 1, right + 1]
30+
elif total > target:
31+
right -= 1
32+
else:
33+
left += 1

0 commit comments

Comments
 (0)