This commit is contained in:
@@ -15,33 +15,34 @@ public class BinarySearch3637 {
|
||||
a.put(Integer.parseInt(args[i]));
|
||||
}
|
||||
|
||||
int start = searchIterativeDecreasing(x, a);
|
||||
int end = searchIterativeIncreasing(x, a.getReversed());
|
||||
if (a.get(start) != x) {
|
||||
System.out.println(0);
|
||||
} else {
|
||||
System.out.println(end - start);
|
||||
}
|
||||
System.out.println(rightBound(x, a) - leftBound(x, a));
|
||||
}
|
||||
|
||||
static int searchIterativeIncreasing(int x, IntList a) {
|
||||
if (a.getLength() == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int leftBound(int x, IntList a) {
|
||||
int low = 0,
|
||||
high = a.getLength() - 1;
|
||||
|
||||
while (low <= high) {
|
||||
int mid = low + (high - low) / 2;
|
||||
if (a.get(mid) >= x) {
|
||||
high = mid - 1;
|
||||
} else {
|
||||
low = mid + 1;
|
||||
}
|
||||
}
|
||||
return low;
|
||||
}
|
||||
|
||||
static int rightBound(int x, IntList a) {
|
||||
int low = 0,
|
||||
high = a.getLength() - 1;
|
||||
while (low <= high) {
|
||||
int mid = low + (high - low) / 2;
|
||||
if (a.get(mid) <= x) {
|
||||
low = mid + 1;
|
||||
} else {
|
||||
high = mid - 1;
|
||||
}
|
||||
}
|
||||
|
||||
return low;
|
||||
}
|
||||
|
||||
|
||||
@@ -28,16 +28,6 @@ public class IntList {
|
||||
return idx;
|
||||
}
|
||||
|
||||
public IntList getReversed() {
|
||||
IntList reverse = new IntList(new int[idx]);
|
||||
|
||||
for (int i = idx - 1; i >= 0; i--) {
|
||||
reverse.put(list[i]);
|
||||
}
|
||||
|
||||
return reverse;
|
||||
}
|
||||
|
||||
public int get(int index) {
|
||||
return list[index];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user