-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMain6.java
52 lines (49 loc) · 1.35 KB
/
Main6.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
42
43
44
45
46
47
48
49
50
51
52
package JZOfferTuJi;
public class Main6 {
// 二分查找
public int[] twoSum(int[] numbers, int target) {
int n = numbers.length;
for(int i=0; i<n-1; i++){
int x = numbers[i];
int index = binarySearch(numbers, i+1, n-1, target - x);
if(index!=-1){
return new int[]{i, index};
}
}
return new int[0];
}
private int binarySearch(int[] numbers, int left, int right, int target){
while(left<=right){
int mid = left + (right - left) / 2;
if(numbers[mid] == target){
return mid;
}else if(numbers[mid]<target){
left = mid + 1;
}else{
right = mid - 1;
}
}
return -1;
}
}
class Main6_1{
// 双指针法
public int[] twoSum(int[] numbers, int target) {
if(numbers == null || numbers.length == 0){
return new int[0];
}
int left = 0;
int right = numbers.length - 1;
while (left < right){
int sum = numbers[left] + numbers[right];
if(sum == target){
return new int[]{left, right};
} else if(sum < target){
left++;
} else{
right--;
}
}
return new int[0];
}
}