
一个数组 arr 被称为山脉数组,需满足以下条件:
简而言之,山脉数组形如“先上升后下降”的山峰状,其峰值是数组中唯一的最大元素。例如,[0, 2, 1, 0] 是一个山脉数组,其峰值索引为 1,对应的值是 2。
最直观的解决方案是遍历整个数组,找到最大值及其对应的索引。由于山脉数组的特性,最大值必然是唯一的峰值。
public class Solution {
public static int peakIndexInMountainArrayLinear(int[] arr) {
int peakValue = arr[0]; // 初始峰值设为第一个元素
int peakIndex = 0;
// 从第二个元素开始遍历,因为第一个元素不可能是峰值(除非数组长度小于3,但山脉数组定义排除此情况)
// 实际上,从arr[0]开始遍历也可以,只要确保peakValue和peakIndex的初始值正确
for (int i = 1; i < arr.length; i++) {
if (arr[i] > peakValue) {
peakValue = arr[i];
peakIndex = i;
} else {
// 一旦遇到下降趋势,说明峰值已经找到,因为山脉数组只有一个峰值
// 进一步优化,可以提前退出循环
break;
}
}
return peakIndex;
}
public static void main(String[] args) {
System.out.println("Set 1: " + peakIndexInMountainArrayLinear(new int[]{0,1,2})); // 2
System.out.println("Set 2: " + peakIndexInMountainArrayLinear(new int[]{0,1,0})); // 1
System.out.println("Set 3: " + peakIndexInMountainArrayLinear(new int[]{0,2,1,0})); // 1
System.out.println("Set 4: " + peakIndexInMountainArrayLinear(new int[]{0,10,5,2})); // 1
System.out.println("Set 5: " + peakIndexInMountainArrayLinear(new int[]{0,100,500,2})); // 2
}
}虽然此方法简单有效,但它不满足 O(log(arr.length)) 的时间复杂度要求。
为了达到 O(logN) 的时间复杂度,我们必须利用二分查找。山脉数组的特性(先递增后递减)使得二分查找成为可能。
二分查找的核心在于每次迭代都能排除掉一半的搜索空间。在山脉数组中,我们可以通过比较中间元素 arr[mid] 与其右侧元素 arr[mid+1] 来判断当前 mid 所在的位置:
public class Solution {
public int peakIndexInMountainArrayBinarySearch(int[] arr) {
int low = 0;
int high = arr.length - 1;
// 循环条件是 low < high,当 low == high 时,表示找到了峰值索引
while (low < high) {
int mid = low + (high - low) / 2; // 防止溢出
// 比较 arr[mid] 和 arr[mid+1]
if (arr[mid] < arr[mid + 1]) {
// 如果 arr[mid] 小于 arr[mid+1],说明当前在上升坡
// 峰值在 mid 的右侧,包括 mid+1
low = mid + 1;
} else {
// 如果 arr[mid] 大于 arr[mid+1],说明当前在下降坡或者 mid 就是峰值
// 峰值可能在 mid,也可能在 mid 的左侧
high = mid;
}
}
// 循环结束时,low == high,这个索引就是峰值
return low;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println("Set 1 (Binary Search): " + sol.peakIndexInMountainArrayBinarySearch(new int[]{0,1,2})); // 2
System.out.println("Set 2 (Binary Search): " + sol.peakIndexInMountainArrayBinarySearch(new int[]{0,1,0})); // 1
System.out.println("Set 3 (Binary Search): " + sol.peakIndexInMountainArrayBinarySearch(new int[]{0,2,1,0})); // 1
System.out.println("Set 4 (Binary Search): " + sol.peakIndexInMountainArrayBinarySearch(new int[]{0,10,5,2})); // 1
System.out.println("Set 5 (Binary Search): " + sol.peakIndexInMountainArrayBinarySearch(new int[]{0,100,500,2})); // 2
}
}通过对比线性扫描和二分查找两种方法,我们可以清楚地看到,在满足特定条件(如山脉数组的单调性)时,二分查找能够显著提升算法效率,将时间复杂度从线性降低到对数级别,这对于处理大规模数据集至关重要。理解并正确应用二分查找是解决此类优化问题的关键。
以上就是求解山脉数组的峰值索引:从线性扫描到二分查找的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号