-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumberSumMatch.java
63 lines (55 loc) · 1.42 KB
/
NumberSumMatch.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
*
*/
package com.visa.practice;
import java.util.HashSet;
import java.util.Set;
/**
* @author yz09
*
*/
public class NumberSumMatch {
/**
* @param args
*/
public static void main(String[] args) {
int[] sortedInput = { -7, -6, -5, 1, 2, 4, 4, 13, 14 };
System.out.println(
"result.." + hasPairToSumInSortedArray(sortedInput, 8));
int[] unsortedInput = { 2, 1, 14, 13, 4, -7, -5, 4, -6 };
System.out.println(
"result.." + hasPairToSuminUnsortedArray(unsortedInput, 8));
}
public static String hasPairToSuminUnsortedArray(int[] input,
int givenSum) {
StringBuilder result = new StringBuilder();
Set<Integer> complimentSet = new HashSet<>();
for (int number : input) {
if (complimentSet.contains(number)) {
result.append((givenSum - number) + "," + number + "\n");
} else {
int compliment = givenSum - number;
complimentSet.add(compliment);
}
}
return result.toString();
}
public static String hasPairToSumInSortedArray(int[] input, int givenSum) {
StringBuilder result = new StringBuilder();
int low = 0;
int high = input.length - 1;
while (low < high) {
int sum = input[low] + input[high];
if (givenSum == sum) {
result.append(input[low] + "," + input[high] + "\n");
low++;
high--;
} else if (givenSum > sum) {
low++;
} else {
high--;
}
}
return result.toString();
}
}