-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayPairSum.java
More file actions
43 lines (34 loc) · 984 Bytes
/
ArrayPairSum.java
File metadata and controls
43 lines (34 loc) · 984 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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package net.reservoircode.searching;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Given an integer array, output all pairs that sum up to a specific value k.
*/
public class ArrayPairSum {
private final int[] array;
private int left, right;
public ArrayPairSum(int[] array) {
this.array = array;
left = 0;
right = array.length - 1;
}
public List<Tuple> find(Integer value) {
Arrays.sort(array);
List<Tuple> tuples = new ArrayList<Tuple>();
while (left < right) {
int sum = array[left] + array[right];
if (sum == value) {
tuples.add(new Tuple(array[left], array[right]));
left += 1;
} else if (sum < value) {
left += 1;
} else {
right -= 1;
}
}
return tuples;
}
public record Tuple(Integer left, Integer right) {
}
}