题解 | #寻找牛群中的最高牛#
寻找牛群中的最高牛
https://www.nowcoder.com/practice/df826dd3f9304c61bb6e13fcf16652c3
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param heights int整型一维数组
* @return int整型
*/
int res = 0;
public int findPeakElement(int[] heights) {
// write code here
int n = heights.length;
int[] newHeights = new int[n + 2];
System.arraycopy(heights, 0, newHeights, 1, n);
newHeights[0] = -1;
newHeights[n + 1] = -1;
find(newHeights, 1, n);
return res - 1;
}
private void find(int[] newHeights, int l, int r) {
if (l > r) {
return;
}
if (l == r) {
res = newHeights[l] > newHeights[res] ? l : res;
return;
}
int mid = (l + r) / 2;
if (newHeights[mid] > newHeights[mid - 1]
&& newHeights[mid] > newHeights[mid + 1]) {
res = newHeights[mid] > newHeights[res] ? mid : res;
find(newHeights, l, mid - 2);
find(newHeights, mid + 2, r);
} else {
if (newHeights[mid] < newHeights[mid - 1]) {
find(newHeights, l, mid - 1);
}
if (newHeights[mid] < newHeights[mid + 1]) {
find(newHeights, mid + 1, r);
}
}
}
}
需要考虑多个峰值中的最大值
查看22道真题和解析