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

Appearance settings

Commit c603bec

Browse filesBrowse files
authored
added twopointers algorithm
1 parent 0a8c483 commit c603bec
Copy full SHA for c603bec

File tree

Expand file treeCollapse file tree

1 file changed

+27
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+27
-0
lines changed

‎Algorithms/twopointers.java

Copy file name to clipboard
+27Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
public boolean twoSum(int[] list, int targetValue) {
2+
3+
//each pointer starts at the opposite end of the sorted list and moves towards the middle
4+
5+
int pointerA = 0;
6+
int pointerB = list.length - 1;
7+
8+
9+
while (pointerA < pointerB) {
10+
//calculates the sum
11+
int sum = list[pointerA] + list[pointerB];
12+
13+
//main checker, check whether sum is larger, smaller, or equal to the target
14+
if (sum == targetValue) {
15+
return true;
16+
17+
// this section decreases the larger value or increases the smaller value depending on if the sum is
18+
// larger or smaller than the target value
19+
} else if (sum < targetValue) {
20+
pointerA++;
21+
} else {
22+
pointerB--;
23+
}
24+
}
25+
26+
return false;
27+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.