-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindThreeSumInArray.java
More file actions
58 lines (49 loc) · 1.95 KB
/
Copy pathFindThreeSumInArray.java
File metadata and controls
58 lines (49 loc) · 1.95 KB
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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class FindThreeSumInArray {
static void findTriplet(List<Integer> input, int sum){
for(int index = 0; index < input.size(); index++){
for(int i = index+1; i < input.size(); i++){
for(int j = i+1; j < input.size(); j++){
if(input.get(index) + input.get(i) + input.get(j) == sum){
System.out.println("found triplet at index: " + input.get(index) + ","+ input.get(i)+","+ input.get(j) +" and sum: " + sum);
}
}
}
}
}
static void findTriplet1(List<Integer> input, int sum){
List<List<Integer>> doubles = new ArrayList<>();
for(int index = 0; index < input.size(); index++){
for(int i = index+1; i < input.size(); i++){
//remove duplies if having i and index values reverse is same
List<Integer> temp = Arrays.asList(input.get(i), input.get(index));
doubles.add(temp);
}
}
doubles.stream().forEach(list -> {
System.out.println(Arrays.toString(list.toArray()));
});
for (Integer integer : input) {
for (List<Integer> aDouble : doubles) {
if (aDouble.get(0) + aDouble.get(1) + integer == sum) {
System.out.println("found triplet at index: " + aDouble.get(0) + "," + aDouble.get(1) + "," + integer + " and sum: " + sum);
}
}
}
}
/**
* given input an sorted array [1,3,4,5,15,30]
* find triplet of the sum is equal to 24
* @param args
*/
public static void main(String[] args){
// List<Integer> input = Arrays.asList(1,3,4,5,15,20);
List<Integer> input = Arrays.asList(1,3);
int sum = 24;
// findTriplet(input, sum);
findTriplet1(input,sum);
}
}