-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSolution009.java
More file actions
57 lines (46 loc) · 1.26 KB
/
Solution009.java
File metadata and controls
57 lines (46 loc) · 1.26 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package algorithm.tmop;
import java.util.Arrays;
/**
* @author: mayuan
* @desc: 寻找和为定值的两个数
* 时间复杂度: O(n)
* 空间复杂度: O(1)
* @date:
*/
public class Solution009 {
public static void main(String[] args) {
int[] array = {1, 2, 4, 5, 7, 11, 15};
final int target = 15;
Arrays.sort(array);
twoSum(array, target);
}
/**
* 在数组有序的情况下(数组无序的情况下,可以采用哈希表)
*
* @param array
* @param target
*/
public static void twoSum(int[] array, int target) {
if (null == array || 1 >= array.length) {
return;
}
int begin = 0;
int end = array.length - 1;
while (begin < end) {
int tmp = array[begin] + array[end];
if (target == tmp) {
System.out.println(array[begin] + ", " + array[end]);
// 如果是输出所有满足条件的数对,则需要增加下面这两条语句
// ++begin;
// --end;
break;
} else {
if (target > tmp) {
++begin;
} else {
--end;
}
}
}
}
}