-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathSolution167.java
41 lines (37 loc) · 1.01 KB
/
Solution167.java
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
31
32
33
34
35
36
37
38
39
40
41
package algorithm.leetcode;
/**
* @author: mayuan
* @desc: 两数之和 II - 输入有序数组
* @date: 2018/08/17
*/
public class Solution167 {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
Solution167 test = new Solution167();
for (int t : test.twoSum(nums, target)) {
System.out.println(t);
}
}
public int[] twoSum(int[] numbers, int target) {
int[] answer = new int[2];
if (null == numbers || 2 > numbers.length) {
return answer;
}
int left = 0;
int right = numbers.length - 1;
while (left < right) {
int temp = numbers[left] + numbers[right];
if (target == temp) {
answer[0] = left + 1;
answer[1] = right + 1;
break;
} else if (target > temp) {
++left;
} else {
--right;
}
}
return answer;
}
}