刷题记录(Find Peak Element Solution)
作者:互联网
Leecode:Find Peak Element Solution(JS解题)
两种思路:一种是遍历,一种是二分法,讲下二分法的思路,找到中间节点位置mid,将位置mid和位置mid+1的两个数相比较,如果nums[mid] > nums[mid+1],说明一定有个峰值在左边,反之则一定有个峰值在右边。
上代码:
解法一:
function findPeakElement(nums: number[]): number {
for(var i=1;i<nums.length;i++){
if(nums[i] < nums[i-1]){
return i-1;
}
}
return nums.length-1;
};
解法二:
function findPeakElement(nums: number[]): number {
if(nums.length < 2) return 0;
return helper(nums,0,nums.length-1)
};
function helper(nums: number[],start:number,end:number){
while(start < end){
var mid1:number = Math.floor((start+end)/2);
var mid2:number = mid1+1;
if(nums[mid1] < nums[mid2]){
start = mid2;
}else{
end = mid1;
}
}
return start;
}
标签:return,nums,mid,number,Solution,start,Peak,end,Element 来源: https://blog.csdn.net/xiongBen1993/article/details/109925436