leetcode 162 寻找峰值 二分

递归写法

int binary_search(int* nums,int left,int right)
{
    if(left==right)
       return left;
    int mid=(left+right)>>1;
    if(nums[mid]<nums[mid+1])
       return binary_search(nums,mid+1,right);
    else
       return binary_search(nums,left,mid);
}
int findPeakElement(int* nums, int numsSize){
    return binary_search(nums,0,numsSize-1);
}

非递归

int findPeakElement(int* nums, int numsSize){
    int left=0,right=numsSize-1,mid;
    while(left<right)
    {
        mid=(left+right)>>1;
        if(nums[mid]<nums[mid+1])
           left=mid+1;
        else
           right=mid;
    }
    return left;
}

你可能感兴趣的:(leetcode,leetcode,算法,数据结构)