Skip to content

Commit ffe2fad

Browse files
committed
Two Sum
1 parent 77d95c2 commit ffe2fad

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

src/easy/TwoSum.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package easy;
2+
3+
/**
4+
* Have the function TwoSum(arr) take the array of integers stored in arr,
5+
* and determine if any two numbers (excluding the first element)
6+
* in the array can sum up to the first element in the array.
7+
* ---
8+
* For example: if arr is [7, 3, 5, 2, -4, 8, 11],
9+
* then there are actually two pairs that sum to the number 7: [5, 2] and [-4, 11].
10+
* ---
11+
* Your program should return all pairs,
12+
* with the numbers separated by a comma,
13+
* in the order the first number appears in the array.
14+
* Pairs should be separated by a space.
15+
* So for the example above, your program would return: 5,2 -4,11
16+
*/
17+
public class TwoSum {
18+
19+
/**
20+
* Two Sum function.
21+
*
22+
* @param arr input array
23+
* @return all pairs
24+
*/
25+
private static String twoSum(int[] arr) {
26+
StringBuilder output = new StringBuilder();
27+
for (int i = 1; i < arr.length; i++) {
28+
for (int j = i + 1; j < arr.length; j++) {
29+
if (arr[i] + arr[j] == arr[0]) {
30+
if (output.length() > 0) {
31+
output.append(" ");
32+
}
33+
output.append(arr[i]).append(",").append(arr[j]);
34+
}
35+
}
36+
}
37+
return output.length() == 0 ? "-1" : output.toString();
38+
}
39+
40+
/**
41+
* Entry point.
42+
*
43+
* @param args command line arguments
44+
*/
45+
public static void main(String[] args) {
46+
var result = twoSum(new int[]{8, 1, 2, 3, 4, 5, 7});
47+
System.out.println(result);
48+
}
49+
50+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy