Skip to content

Commit 7de035b

Browse files
committed
TWO-SUM-II
1 parent 2b13602 commit 7de035b

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Two-pointers/twosumII.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"Leetcode- https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/"
2+
'''
3+
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.
4+
5+
Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.
6+
7+
The tests are generated such that there is exactly one solution. You may not use the same element twice.
8+
9+
Your solution must use only constant extra space.
10+
11+
Example 1:
12+
13+
Input: numbers = [2,7,11,15], target = 9
14+
Output: [1,2]
15+
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
16+
'''
17+
def twoSum(self, numbers, target):
18+
l, r = 0, len(numbers)-1
19+
while l < r:
20+
sum = numbers[l] + numbers[r]
21+
if sum < target:
22+
l += 1
23+
elif sum > target:
24+
r -= 1
25+
else:
26+
return [l+1, r+1]
27+
28+
#T:O(N)
29+
#S:O(1)

0 commit comments

Comments
 (0)