Skip to content

Commit 0a5334e

Browse files
authored
Merge pull request #770 from shashank-0-0/working
Made changes to the TwoSum problem
2 parents e3efdf6 + 03a4dff commit 0a5334e

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

LeetCode/1. Two Sum/Solution.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,26 @@ public int[] twoSum(int[] nums, int target) {
1313
return null;
1414
}
1515
}
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)

0 commit comments

Comments
 (0)