-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode0167.java
More file actions
30 lines (28 loc) · 915 Bytes
/
Copy pathLeetCode0167.java
File metadata and controls
30 lines (28 loc) · 915 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
/* Two Sum II - Input array is sorted
* Input: numbers = [2,7,11,15], target = 9
* Output: [1,2]
* Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
* */
public class LeetCode0167 {
public static void main(String args[]) {
int[] numbers = {-1, 0};
int target = -1;
int[] res = twoSum(numbers, target);
for (int i : res)
System.out.print(i + ",");
}
public static int[] twoSum(int[] numbers, int target) {
if (numbers == null || numbers.length == 0)
return null;
int i = 0, j = numbers.length - 1;
while (i < j) {
if (numbers[i] + numbers[j] == target)
return new int[]{i + 1, j + 1};
else if (numbers[i] + numbers[j] > target)
j--;
else
i++;
}
return null;
}
}