Uh oh!
There was an error while loading. Please reload this page.
forked from liuyubobobo/Play-with-Algorithm-Interview
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution3.java
More file actions
Latest commit
49 lines (40 loc) · 1.33 KB
/
Copy pathSolution3.java
File metadata and controls
49 lines (40 loc) · 1.33 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
// 167. Two Sum II - Input array is sorted
// https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/
//
// 对撞指针
// 时间复杂度: O(n)
// 空间复杂度: O(1)
publicclassSolution3 {
publicint[] twoSum(int[] numbers, inttarget) {
if(numbers.length < 2/*|| !isSorted(numbers)*/)
thrownewIllegalArgumentException("Illegal argument numbers");
intl = 0, r = numbers.length - 1;
while(l < r){
if(numbers[l] + numbers[r] == target){
int[] res = {l+1, r+1};
returnres;
}
elseif(numbers[l] + numbers[r] < target)
l ++;
else// numbers[l] + numbers[r] > target
r --;
}
thrownewIllegalStateException("The input has no solution");
}
privatebooleanisSorted(int[] numbers){
for(inti = 1 ; i < numbers.length ; i ++)
if(numbers[i] < numbers[i-1])
returnfalse;
returntrue;
}
privatestaticvoidprintArr(int[] nums){
for(intnum: nums)
System.out.print(num + " ");
System.out.println();
}
publicstaticvoidmain(String[] args) {
int[] nums = {2, 7, 11, 15};
inttarget = 9;
printArr((newSolution3()).twoSum(nums, target));
}
}