-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpairsum.java
More file actions
49 lines (46 loc) · 1.42 KB
/
Copy pathpairsum.java
File metadata and controls
49 lines (46 loc) · 1.42 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
package arraylist;
import java.util.*;
public class pairsum {
//brute force
public static void pair(ArrayList<Integer> list,int target){
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
for (int j = i+1; j < list.size(); j++) {
if(list.get(i)+list.get(j)==target){
System.out.println(list.get(i)+","+list.get(j));
}
}
}
}
//two pointer approach
public static void pairsopti(ArrayList<Integer> list, int target){
Collections.sort(list);
int lp=0;
int rp=list.size()-1;
while(lp<rp){
if(list.get(rp)+list.get(lp)==target){
System.out.println(list.get(lp)+","+list.get(rp));
int leftVal = list.get(lp);
int rightVal = list.get(rp);
while(lp < rp && list.get(lp) == leftVal) lp++;
while(lp < rp && list.get(rp) == rightVal) rp--;
}else if(list.get(rp)+list.get(lp)<target){
lp++;
}else{
rp--;
}
}
}
public static void main(String[] args) {
ArrayList<Integer> list=new ArrayList<>();
list.add(1);
list.add(2);
list.add(5);
list.add(4);
list.add(3);
list.add(6);
int target=8;
pair(list, target);
pairsopti(list, target);
}
}