Skip to content

Commit eb8c870

Browse files
author
wangpeng
committed
feat(EASY): 167_twoSum
1 parent e3b6d38 commit eb8c870

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package pp.arithmetic.leetcode;
2+
3+
import pp.arithmetic.Util;
4+
5+
/**
6+
* Created by wangpeng on 2019-03-20.
7+
* 167. 两数之和 II - 输入有序数组
8+
* <p>
9+
* 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
10+
* <p>
11+
* 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
12+
* <p>
13+
* 说明:
14+
* <p>
15+
* 返回的下标值(index1 和 index2)不是从零开始的。
16+
* 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
17+
* 示例:
18+
* <p>
19+
* 输入: numbers = [2, 7, 11, 15], target = 9
20+
* 输出: [1,2]
21+
* 解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
22+
*
23+
* @see <a href="https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/">two-sum-ii-input-array-is-sorted</a>
24+
*/
25+
public class _167_twoSum {
26+
27+
public static void main(String[] args) {
28+
_167_twoSum twoSum = new _167_twoSum();
29+
Util.printArray(twoSum.twoSum(new int[]{2, 7, 11, 15}, 9));
30+
}
31+
32+
public int[] twoSum(int[] numbers, int target) {
33+
int[] result = new int[2];
34+
int startI = 0, endI = numbers.length - 1;
35+
while (startI < endI) {
36+
int add = numbers[startI] + numbers[endI];
37+
if (add == target) {
38+
result[0] = startI + 1;
39+
result[1] = endI + 1;
40+
break;
41+
} else if (add > target) {
42+
endI--;
43+
} else {
44+
startI++;
45+
}
46+
}
47+
return result;
48+
}
49+
}

0 commit comments

Comments
 (0)