Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit dcfe111

Browse files
committed
added: two sum II
1 parent 0492572 commit dcfe111

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# two sum II - input array is sorted | leetcode 167 | https://leetcode.com/problems/two-sum-ii-input-array-is-sorted
2+
# use two pointers on sorted array; if sum > target slide window left, else slide window right
3+
4+
class Solution:
5+
def twoSum(self, numbers: list[int], target: int) -> list[int]:
6+
ptrL = 0
7+
ptrR = 1
8+
N = len(numbers)
9+
10+
while ptrR < N:
11+
s = numbers[ptrR] + numbers[ptrL]
12+
if s == target:
13+
return [ptrL + 1, ptrR + 1]
14+
elif s < target:
15+
ptrL += 1
16+
ptrR += 1
17+
else:
18+
ptrL -= 1
19+
20+
# unreachable for testcases with exactly one solution
21+
return [-1, -1]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /