forked from liuyubobobo/Play-with-Algorithm-Interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution2.java
65 lines (52 loc) · 1.78 KB
/
Solution2.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
53
54
55
56
57
58
59
60
61
62
63
64
65
// 167. Two Sum II - Input array is sorted
// https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/
//
// 二分搜索法
// 时间复杂度: O(nlogn)
// 空间复杂度: O(1)
public class Solution2 {
public int[] twoSum(int[] numbers, int target) {
if(numbers.length < 2 /*|| !isSorted(numbers)*/)
throw new IllegalArgumentException("Illegal argument numbers");
for(int i = 0 ; i < numbers.length - 1 ; i ++){
int j = binarySearch(numbers, i+1, numbers.length-1, target - numbers[i]);
if(j != -1){
int[] res = {i+1, j+1};
return res;
}
}
throw new IllegalStateException("The input has no solution");
}
private int binarySearch(int[] nums, int l, int r, int target){
if(l < 0 || l > nums.length)
throw new IllegalArgumentException("l is out of bound");
if(r < 0 || r > nums.length)
throw new IllegalArgumentException("r is out of bound");
while(l <= r){
int mid = l + (r - l)/2;
if(nums[mid] == target)
return mid;
if(target > nums[mid])
l = mid + 1;
else
r = mid - 1;
}
return -1;
}
private boolean isSorted(int[] numbers){
for(int i = 1 ; i < numbers.length ; i ++)
if(numbers[i] < numbers[i-1])
return false;
return true;
}
private static void printArr(int[] nums){
for(int num: nums)
System.out.print(num + " ");
System.out.println();
}
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
printArr((new Solution2()).twoSum(nums, target));
}
}