Skip to content

Commit 66dcb3f

Browse files
committed
add solution of problem 167: Two Sum II - Input Array Is Sorted
1 parent 0916443 commit 66dcb3f

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
Given an array of integers that is already ***sorted in ascending order***, find two numbers such that they add up to a specific target number.
2+
3+
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
4+
5+
You may assume that each input would have exactly one solution.
6+
7+
**Input:** numbers={2, 7, 11, 15}, target=9
8+
9+
**Output:** index1=1, index2=2
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
public class Solution {
2+
public int[] twoSum(int[] numbers, int target) {
3+
int[] result = {0, 0};
4+
if (numbers == null || numbers.length <= 1)
5+
return result;
6+
7+
int index1 = 0;
8+
int index2 = numbers.length - 1;
9+
10+
while (index1 < index2) {
11+
int sum = numbers[index1] + numbers[index2];
12+
if (sum < target)
13+
index1++;
14+
else if (sum > target)
15+
index2--;
16+
else
17+
break;
18+
}
19+
20+
result[0] = index1 + 1;
21+
result[1] = index2 + 1;
22+
return result;
23+
}
24+
}

0 commit comments

Comments
 (0)