Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathTwoPointers.java
More file actions
Latest commit
45 lines (39 loc) · 1.24 KB
/
Copy pathTwoPointers.java
File metadata and controls
45 lines (39 loc) · 1.24 KB
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
39
40
41
42
43
44
45
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/
*/
publicfinalclassTwoPointers {
privateTwoPointers() {
}
/**
* Checks whether there exists a pair of elements in a sorted array whose sum equals the specified key.
*
* @param arr a sorted array of integers in ascending order (must not be null)
* @param key the target sum to find
* @return {@code true} if there exists at least one pair whose sum equals {@code key}, {@code false} otherwise
* @throws IllegalArgumentException if {@code arr} is {@code null}
*/
publicstaticbooleanisPairedSum(int[] arr, intkey) {
if (arr == null) {
thrownewIllegalArgumentException("Input array must not be null.");
}
intleft = 0;
intright = arr.length - 1;
while (left < right) {
intsum = arr[left] + arr[right];
if (sum == key) {
returntrue;
}
if (sum < key) {
left++;
} else {
right--;
}
}
returnfalse;
}
}