mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 17:29:31 +08:00
refactor: TwoPointers
(#5380)
This commit is contained in:
@ -1,39 +1,33 @@
|
||||
package com.thealgorithms.others;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* The two pointer technique is a useful tool to utilize when searching for
|
||||
* 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/
|
||||
* Link: https://www.geeksforgeeks.org/two-pointers-technique/
|
||||
*/
|
||||
final class TwoPointers {
|
||||
private TwoPointers() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a sorted array arr (sorted in ascending order). Find if there
|
||||
* exists any pair of elements such that their sum is equal to key.
|
||||
* 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 contains elements
|
||||
* @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.
|
||||
* @return {@code true} if there exists a pair of elements, {@code false} otherwise.
|
||||
*/
|
||||
public static boolean isPairedSum(int[] arr, int key) {
|
||||
/* array sorting is necessary for this algorithm to function correctly */
|
||||
Arrays.sort(arr);
|
||||
int i = 0;
|
||||
/* index of first element */
|
||||
int j = arr.length - 1;
|
||||
/* index of last element */
|
||||
int i = 0; // index of the first element
|
||||
int j = arr.length - 1; // index of the last element
|
||||
|
||||
while (i < j) {
|
||||
if (arr[i] + arr[j] == key) {
|
||||
int sum = arr[i] + arr[j];
|
||||
if (sum == key) {
|
||||
return true;
|
||||
} else if (arr[i] + arr[j] < key) {
|
||||
} else if (sum < key) {
|
||||
i++;
|
||||
} else {
|
||||
j--;
|
||||
|
Reference in New Issue
Block a user