mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-10 16:00:36 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
@@ -7,43 +7,43 @@
|
||||
package chapter_searching;
|
||||
|
||||
public class binary_search_edge {
|
||||
/* Binary search for the leftmost target */
|
||||
/* Find the leftmost occurrence of target using binary search */
|
||||
static int binarySearchLeftEdge(int[] nums, int target) {
|
||||
// Equivalent to finding the insertion point of target
|
||||
// This is equivalent to finding the insertion point of target
|
||||
int i = binary_search_insertion.binarySearchInsertion(nums, target);
|
||||
// Target not found, return -1
|
||||
// If target was not found, return -1
|
||||
if (i == nums.length || nums[i] != target) {
|
||||
return -1;
|
||||
}
|
||||
// Found target, return index i
|
||||
// Target was found; return index i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Binary search for the rightmost target */
|
||||
/* Find the rightmost occurrence of target using binary search */
|
||||
static int binarySearchRightEdge(int[] nums, int target) {
|
||||
// Convert to finding the leftmost target + 1
|
||||
// Reduce the problem to finding the leftmost insertion point of target + 1
|
||||
int i = binary_search_insertion.binarySearchInsertion(nums, target + 1);
|
||||
// j points to the rightmost target, i points to the first element greater than target
|
||||
// j points to the rightmost target, while i points to the first element greater than target
|
||||
int j = i - 1;
|
||||
// Target not found, return -1
|
||||
// If target was not found, return -1
|
||||
if (j == -1 || nums[j] != target) {
|
||||
return -1;
|
||||
}
|
||||
// Found target, return index j
|
||||
// Target was found; return index j
|
||||
return j;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Array with duplicate elements
|
||||
// Array containing duplicate elements
|
||||
int[] nums = { 1, 3, 6, 6, 6, 6, 6, 10, 12, 15 };
|
||||
System.out.println("\nArray nums = " + java.util.Arrays.toString(nums));
|
||||
|
||||
// Binary search left and right boundaries
|
||||
// Find the left and right boundaries using binary search
|
||||
for (int target : new int[] { 6, 7 }) {
|
||||
int index = binarySearchLeftEdge(nums, target);
|
||||
System.out.println("Index of leftmost element " + target + " is " + index);
|
||||
System.out.println("Leftmost occurrence of " + target + " has index " + index);
|
||||
index = binarySearchRightEdge(nums, target);
|
||||
System.out.println("Index of rightmost element " + target + " is " + index);
|
||||
System.out.println("Rightmost occurrence of " + target + " has index " + index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user