File tree Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Original file line number Diff line number Diff line change @@ -13,3 +13,26 @@ public int[] twoSum(int[] nums, int target) {
13
13
return null ;
14
14
}
15
15
}
16
+ //Two pointer method
17
+ //If the array is sorted and you want to check if there exists two numbers adding to a given sum or not.
18
+ class Solution {
19
+ public boolean twoSum (int [] nums , int target ) {
20
+ int i =0 ;
21
+ int j =nums .length -1 ;
22
+ while (i <j ){
23
+ int sum =nums [i ]+nums [j ];
24
+ if (sum ==target ){
25
+ return true ;
26
+ }else if (sum <target ){
27
+ //if the sum is lesser then we increase the i pointer cuz we need a larger value to make the sum.(array is sorted)
28
+ i ++;
29
+ }else {
30
+ //if the sum is greater then we decrease the j pointer cuz we need a smaller value.
31
+ j --;
32
+ }
33
+ }
34
+ return false ;
35
+ }
36
+ }
37
+ Time complexity =O (n )
38
+ space complexity =O (1 )
You can’t perform that action at this time.
0 commit comments