forked from sPredictorX1708/Ultimate-Java-Resources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwopointers.java
More file actions
27 lines (20 loc) · 805 Bytes
/
twopointers.java
File metadata and controls
27 lines (20 loc) · 805 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public boolean twoSum(int[] list, int targetValue) {
//each pointer starts at the opposite end of the sorted list and moves towards the middle
int pointerA = 0;
int pointerB = list.length - 1;
while (pointerA < pointerB) {
//calculates the sum
int sum = list[pointerA] + list[pointerB];
//main checker, check whether sum is larger, smaller, or equal to the target
if (sum == targetValue) {
return true;
// this section decreases the larger value or increases the smaller value depending on if the sum is
// larger or smaller than the target value
} else if (sum < targetValue) {
pointerA++;
} else {
pointerB--;
}
}
return false;
}