-
Notifications
You must be signed in to change notification settings - Fork 130
/
Copy pathTargetSum.java
39 lines (34 loc) · 1.02 KB
/
TargetSum.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
39
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class TargetSum {
public boolean hasPair(int[] values, int expectedSum) {
Arrays.sort(values);
int left = 0;
int right = values.length - 1;
for (; left < right; ) {
int actualSum = values[left] + values[right];
if (actualSum > expectedSum) {
right--;
} else if (actualSum < expectedSum) {
left++;
} else {
return true;
}
}
return false;
}
public boolean hasPairUsingSet(int[] values, int expectedSum) {
Set<Integer> seenValues = new HashSet<>();
for (int value : values) {
int diff = expectedSum - value;
if (!seenValues.contains(diff)) {
seenValues.add(value);
} else {
//Found it is diffvalue & currvalue that wil make up sum
return true;
}
}
return false;
}
}