-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwoSum2.java
More file actions
30 lines (27 loc) · 743 Bytes
/
twoSum2.java
File metadata and controls
30 lines (27 loc) · 743 Bytes
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
// You get passed an array of numbers. Find the indices of two numbers that add upto a particlar target twoSum
// assume that there is only one solution
//but as opposed to twoSum1, here the input is a sorted array
class twoSum2{
public static int[] twoSum(int[] nums,int target){
int i=0;
int j=nums.length-1;
//i and j point to the extreme ends of the sorted array
while(i<j){
int a=nums[i]+nums[j];
if(a>target)
j--;
else if(a<target)
i++;
else
break;
}
return new int[] {i,j};
}
public static void main(String[] args){
int[] nums= {1,2,3,4,6};
int target=7;
int[] ans=twoSum(nums,target);
for(int i:ans)
System.out.println(i+" "); //returns 0,4 corresponding to 1 and 6 where 1+6=7
}
}