-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSumII.java
More file actions
33 lines (31 loc) · 934 Bytes
/
TwoSumII.java
File metadata and controls
33 lines (31 loc) · 934 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
31
32
33
package com.leetcode;
/**
* Created by jamylu on 2018/1/7.
* leetcode167.
* 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.
*/
public class TwoSumII {
public static void main(String[] args) {
int numbers[] = {2, 7, 9, 11};
int target = 9;
for (int i = 0; i < 2; i++) {
System.out.println(sum(numbers, target)[i]);
}
}
//双指针,一个向后,一个向前 O(n)
public static int[] sum(int[] numbers, int target) {
int i = 0;
int j = numbers.length - 1;
while (j > i) {
if (numbers[i] + numbers[j] == target) {
return new int[]{++i, ++j};
} else if (numbers[i] + numbers[j] < target) {
i++;
} else {
j--;
}
}
return new int[2];
}
}