阅读量:0
要使用Java进行二分查找数组中具有相同元素的方法,首先需要确保数组已经按照升序或降序的方式排序。然后,可以使用以下代码来实现二分查找:
public class BinarySearch { public static void main(String[] args) { int[] nums = {1, 2, 3, 3, 4, 5, 6}; int target = 3; int left = binarySearchLeft(nums, target); int right = binarySearchRight(nums, target); if (left == -1 || right == -1) { System.out.println("No elements found."); } else { for (int i = left; i <= right; i++) { System.out.println("Element found at index: " + i); } } } public static int binarySearchLeft(int[] nums, int target) { int left = 0; int right = nums.length - 1; int index = -1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) { index = mid; right = mid - 1; } else if (nums[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return index; } public static int binarySearchRight(int[] nums, int target) { int left = 0; int right = nums.length - 1; int index = -1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) { index = mid; left = mid + 1; } else if (nums[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return index; } }
在这个例子中,我们定义了两个辅助函数binarySearchLeft
和binarySearchRight
来查找数组中具有相同元素的左右边界。然后在main
方法中调用这两个函数,并打印出所有满足条件的元素的索引。