From c750d92329ea56996a740e878cf98c41ad2b2eaa Mon Sep 17 00:00:00 2001 From: me Date: Tue, 17 Feb 2026 13:30:13 +0300 Subject: [PATCH] update 3637 mod solution --- java/search/BinarySearch3637.java | 64 +++++++++++++------------------ 1 file changed, 26 insertions(+), 38 deletions(-) diff --git a/java/search/BinarySearch3637.java b/java/search/BinarySearch3637.java index ceb50fb..6b74f58 100644 --- a/java/search/BinarySearch3637.java +++ b/java/search/BinarySearch3637.java @@ -12,10 +12,14 @@ public class BinarySearch3637 { for (int i = 1; i < n; i++) { a.put(Integer.parseInt(args[i])); } - System.out.println(rightBound(x, a) - leftBound(x, a)); + // System.out.println(rightBoundIterative(x, a) - leftBoundIterative(x, a)); + System.out.println( + rightBoundRecursive(x, a, 0, a.getLength()) - + leftBoundRecursive(x, a, 0, a.getLength()) + ); } - static int leftBound(int x, IntList a) { + static int leftBoundIterative(int x, IntList a) { int low = 0, high = a.getLength() - 1; while (low <= high) { @@ -29,7 +33,7 @@ public class BinarySearch3637 { return high + 1; } - static int rightBound(int x, IntList a) { + static int rightBoundIterative(int x, IntList a) { int low = 0, high = a.getLength() - 1; while (low <= high) { @@ -43,47 +47,31 @@ public class BinarySearch3637 { return high + 1; } - static int searchIterativeDecreasing(int x, IntList a) { - if (a.getLength() == 0) { - return 0; - } - - 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 searchRecursive(int x, IntList a) { - return searchRecursiveHelper(x, a, 0, a.getLength() - 1); - } - - private static int searchRecursiveHelper( - int x, - IntList a, - int low, - int high - ) { + static int leftBoundRecursive(int x, IntList a, int low, int high) { if (low > high) { - return low; + return high + 1; } int mid = low + (high - low) / 2; - if (a.get(mid) <= x) { - return searchRecursiveHelper(x, a, low, mid - 1); + if (a.get(mid) > x) { + return leftBoundRecursive(x, a, mid + 1, high); } else { - return searchRecursiveHelper(x, a, mid + 1, high); + return leftBoundRecursive(x, a, low, mid - 1); + } + } + + static int rightBoundRecursive(int x, IntList a, int low, int high) { + if (low > high) { + return high + 1; + } + + int mid = low + (high - low) / 2; + + if (a.get(mid) >= x) { + rightBoundRecursive(x, a, mid + 1, high); + } else { + rightBoundRecursive(x, a, low, mid - 1); } } }