diff --git a/java/search/BinarySearch3637.java b/java/search/BinarySearch3637.java index d616c9b..062dcbd 100644 --- a/java/search/BinarySearch3637.java +++ b/java/search/BinarySearch3637.java @@ -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; } diff --git a/java/search/IntList.java b/java/search/IntList.java index 8801fa6..ad312df 100644 --- a/java/search/IntList.java +++ b/java/search/IntList.java @@ -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]; }