-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreesum.java
More file actions
36 lines (35 loc) · 1.13 KB
/
threesum.java
File metadata and controls
36 lines (35 loc) · 1.13 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
import java.util.Arrays;
/*
* in this program we are using two pointer algorithm to find 3 numbers whose
* sum is equal to the target given from the array.
* compared to the bruteforce and hashmap method time and space complexity is reduce using two pointer alogorithm.
*/
public class threesum {
public static void main(String [] args){
int arr[] = {7, -6, 3, 8, -1, 8, -11};
int target = 0;
solution(arr, target, arr.length);
}
public static void solution(int a[], int target, int n){
Arrays.sort(a);
for(int i=0; i<n; i++){
if(i==0 || (a[i] != a[i-1])){
int j = i+1, k= n-1;
int tar = target - a[i];
while(j<k){
if(a[j] + a[k] == tar){
System.out.println(a[i]+ " " + a[j] + " " + a[k]);
while(j<k && a[j] == a[j+1]) j++;
while(j<k && a[k] == a[k-1]) k--;
j++;
k--;
}else if(a[j] + a[k] < tar){
j++;
}else{
k--;
}
}
}
}
}
}