Skip to content

Commit 5ddf40b

Browse files
committed
Add two sum 2
1 parent 308a431 commit 5ddf40b

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
Code
2+
====
3+
4+
```go
5+
func twoSum(numbers []int, target int) []int {
6+
7+
nums := numbers
8+
9+
lb := 0
10+
ub := len(nums) - 1
11+
12+
for ub > lb {
13+
sum := nums[ub] + nums[lb]
14+
15+
if sum == target {
16+
return []int{lb + 1, ub + 1}
17+
} else if sum < target {
18+
for lb < ub && nums[lb+1] == nums[lb] {
19+
lb++
20+
}
21+
lb++
22+
} else {
23+
for lb < ub && nums[ub] == nums[ub-1] {
24+
ub--
25+
}
26+
ub--
27+
}
28+
}
29+
30+
return []int{0, 0}
31+
}
32+
```
33+
34+
Solution in mind
35+
================
36+
37+
- Since the array i sorted, we make use of two pointers, upper bound (ub) and lower bound (lb).
38+
39+
- We initialise ub, lb to `len(nums)-1` and 0 respectively. We check if the sum of elements at these indices are equal to target. If yes, we return indices.
40+
41+
- If the sum is lesser, we move the lower bound pointer higher up. If greater, we bring the upper bound pointer down.

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ My collection of leet code problems solved in GoLang!
55

66
| [Easy](#easy) | [Medium](#medium) | [Hard](#hard) |
77
|---------------|-------------------|---------------|
8-
| 22 | 37 | 8 |
8+
| 23 | 37 | 8 |
99

1010
Problems finished
1111
=================
@@ -57,6 +57,8 @@ Easy
5757

5858
- [range-sum-of-bst](Easy/range-sum-of-bst.md)
5959

60+
- [two-sum-ii-input-array-is-sorted](Easy/two-sum-ii-input-array-is-sorted.md)
61+
6062
Medium
6163
------
6264

0 commit comments

Comments
 (0)