题解 | #KiKi学结构体和指针#
寻找峰值
http://www.nowcoder.com/practice/fcf87540c4f347bcb4cf720b5b350c76
峰值
1.如果数组长度为0或者1 直接返回0 2.首先找两端点是不是比旁边的值大 大就是峰值直接返回 3.找一个变量索引中值 利用二分法不断缩小范围 返回最后的索引中值变量
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型
*/
public int findPeakElement (int[] nums) {
// write code here
if(nums == null){
return 0;
}
if(nums.length == 1){
return 0;
}
if(nums[0] > nums[1]){
return 0;
}
if(nums[nums.length-1] > nums[nums.length-2]){
return nums.length - 1;
}
int L = 0;
int R = nums.length - 1;
int index = L + ((R-L)>>1);
while(L < R){
if(nums[index] > nums[index-1] && nums[index] > nums[index+1]){
return index;
}
if(nums[index] < nums[index-1]){
R = index - 1;
index = L + ((R-L)>>1);
}
if(nums[index] < nums[index+1]){
L = index + 1;
index = L + ((R-L)>>1);
}
}
return index;
// int L = 0;
// int R = nums.length-1;
// while(L < R){
// int index = L + ((R-L)>>1);
// if(nums[index] > nums[index+1]){
// R = index;
// }else{
// L = index + 1;
// }
// }
// return R;
}
}
