- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathTwoPointers.java
38 lines (35 loc) · 1.09 KB
/
TwoPointers.java
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
28
29
30
31
32
33
34
35
36
37
38
packagecom.thealgorithms.others;
/**
* The two-pointer technique is a useful tool to utilize when searching for
* pairs in a sorted array.
*
* <p>
* Link: https://www.geeksforgeeks.org/two-pointers-technique/
*/
finalclassTwoPointers {
privateTwoPointers() {
}
/**
* Given a sorted array arr (sorted in ascending order), find if there exists
* any pair of elements such that their sum is equal to the key.
*
* @param arr the array containing elements (must be sorted in ascending order)
* @param key the number to search
* @return {@code true} if there exists a pair of elements, {@code false} otherwise.
*/
publicstaticbooleanisPairedSum(int[] arr, intkey) {
inti = 0; // index of the first element
intj = arr.length - 1; // index of the last element
while (i < j) {
intsum = arr[i] + arr[j];
if (sum == key) {
returntrue;
} elseif (sum < key) {
i++;
} else {
j--;
}
}
returnfalse;
}
}