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