
考虑一个排序数组,例如:
[1, 2, 3, 4, 5, 6]
现在,如果这个数组在某个枢轴处旋转,比如在索引 3 处,它将变成:
[4, 5, 6, 1, 2, 3]
请注意,数组仍然是排序的,但它被分为两部分。我们的目标是有效地在此类数组中搜索目标值。
要在旋转排序数组中搜索,我们需要:
class Solution {
public static void main(String[] args) {
int[] arr = {4, 5, 6, 1, 2, 3}; // Example of rotated sorted array
int target = 5;
// Searching for the target
int result = search(arr, target);
// Displaying the result
System.out.println("Index of target: " + result);
}
// Main search function to find the target in a rotated sorted array
public static int search(int[] nums, int target) {
// Step 1: Find the pivot
int pivot = searchPivot(nums);
// Step 2: If no pivot, perform regular binary search
if (pivot == -1) {
return binarySearch(nums, target, 0, nums.length - 1);
}
// Step 3: If the target is at the pivot, return the pivot index
if (nums[pivot] == target) {
return pivot;
}
// Step 4: Decide which half of the array to search
if (target >= nums[0]) {
return binarySearch(nums, target, 0, pivot - 1); // Search left side
} else {
return binarySearch(nums, target, pivot + 1, nums.length - 1); // Search right side
}
}
// Binary search helper function
static int binarySearch(int[] arr, int target, int start, int end) {
while (start <= end) {
int mid = start + (end - start) / 2;
if (arr[mid] == target) {
return mid; // Target found
} else if (target < arr[mid]) {
end = mid - 1; // Search left half
} else {
start = mid + 1; // Search right half
}
}
return -1; // Target not found
}
// Function to find the pivot index in a rotated sorted array
static int searchPivot(int[] arr) {
int start = 0;
int end = arr.length - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
// Check if mid is the pivot point
if (mid < end && arr[mid] > arr[mid + 1]) {
return mid;
}
// Check if the pivot is before the mid
if (mid > start && arr[mid] < arr[mid - 1]) {
return mid - 1;
}
// Decide whether to move left or right
if (arr[mid] <= arr[start]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1; // No pivot found (array is not rotated)
}
}
搜索():
binarysearch():
立即学习“Java免费学习笔记(深入)”;
searchpivot():
对于像 [4, 5, 6, 1, 2, 3] 这样的数组:
此方法确保我们高效搜索,实现 o(log n) 的时间复杂度,类似于标准的二分搜索。
旋转排序数组是一个常见的面试问题,也是加深您对二分搜索理解的有用挑战。通过找到枢轴并相应地调整我们的二分搜索,我们可以在对数时间中高效地搜索数组。
如果您觉得这篇文章有帮助,请随时在 linkedin 上与我联系或在评论中分享您的想法!快乐编码!
以上就是用 Java 构建旋转排序数组搜索:了解枢轴搜索和二分搜索的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号