-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwo Sum -II Input Array Sorted
53 lines (41 loc) · 1.21 KB
/
Two Sum -II Input Array Sorted
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
#
//Approach 1:
class Solution {
public int[] twoSum(int[] numbers, int target) {
int i=0;
int j=numbers.length-1;
while(i<j){
if((numbers[i]+numbers[j])<target)
{
i++;
}
else if((numbers[i]+numbers[j])>target)
{
j--;
}
else{
return new int[]{i+1,j+1};
}
}
return new int[]{-1,-1};
}
}
Approach 2: Binary Search:
class Solution {
public int[] twoSum(int[] numbers, int target) {
for (int i = 0; i < numbers.length; ++i) {
int low = i + 1;
int high = numbers.length - 1;
while (low <= high) {
int mid = (high - low) / 2 + low;
if (numbers[mid] +numbers[i] == target)
return new int[]{i + 1, mid + 1};
else if (numbers[mid] + numbers[i] > target)
high = mid - 1;
else
low = mid + 1;
}
}
return new int[]{-1, -1};
}
}