-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathTwo Pointer Approach
More file actions
48 lines (41 loc) · 1.2 KB
/
Two Pointer Approach
File metadata and controls
48 lines (41 loc) · 1.2 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
public class TwoPointer {
public static void main(String[] args) {
int array [] = {6,7,8,9,12,13,14,15};
int k = 27;
// Brute force approach
for(int i=0;i<array.length;i++) {
for(int j= i+1;j<array.length-1;j++) {
if(array[i]+array[j] == k) {
System.out.println("indices found"+ i +j);
}
}
}
// Two pointer approach optimize way time complexity 0(n)
int start=0;
int end= array.length-1;
while(start<=end) {
if(start==end) {
System.out.println("Not Found");
break;
}
if(array[start]+array[end]>k) {
end--;
} else if(array[start]+array[end]<k) {
start++;
} else {
// sum mil jaye
System.out.println("we found the indices "+ start+ "," + end);
break;
}
}
// Break example
// int k1=100;
// while(k>0) {
// if(k1==99) {
// break;
// }
// System.out.println(k1);
// k1--;
// }
}
}