题解 | 寻找峰值
寻找峰值
https://www.nowcoder.com/practice/fcf87540c4f347bcb4cf720b5b350c76
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型
*/
public int findPeakElement (int[] nums) {
// write code here
if(nums.length == 1){
return 0;
}
int i = 0, j = nums.length - 1;
while( i+1 < nums.length && j - 1 >= 0 && nums[i] < nums[i+1] && nums[j-1] > nums[j]){
i++;
j--;
}
if(i == 0){
if(nums[i] < nums[i+1]){
return j;
}
}
if(j == nums.length - 1){
if(nums[j-1] > nums[j]){
return i;
}
}
return i;
}
}
定义两个指针,一个从前向后找,一个从后向前找,其中一个找到就停止,用时236ms,而题解二分查找用时260ms