-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwoSum_167.java
39 lines (32 loc) · 1.03 KB
/
TwoSum_167.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
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
boolean isFound = false;
for(int i = 0; i < numbers.length && !isFound; i++) {
int num = target - numbers[i];
int resultNum = binarySearch(numbers, num, i+1);
if (resultNum > 0) {
result[0] = i+1;
result[1] = resultNum+1;
isFound = true;
break;
}
}
return result;
}
public int binarySearch(int[] numbers, int num, int start) {
int end = numbers.length - 1;
int mid = 0;
while(start <= end) {
mid = (start + end) / 2;
if (numbers[mid] < num) {
start = mid + 1;
} else if (numbers[mid] > num) {
end = mid - 1;
} else {
return mid;
}
}
return 0;
}
}