leetcode_1095. Find in Mountain Array_[Binary Search]

https://leetcode.com/problems/find-in-mountain-array/

题意:给定一个MountainArray(定义见题目),找到其中最早出现的target值的下标。

MountainArray.get() 函数调用不能超过100次。

解法:首先使用Binary Search找到mountain的peak,将array分为一个严格递增和一个严格递减的array,然后使用Binary Search。

class Solution
{
public:
    int find_peak(MountainArray &mountainArr)
    {
        int l=0, r=mountainArr.length()-1;
        while(l<=r)
        {
            int m=(l+r)/2;
            int m_val=mountainArr.get(m);
            int m_r_val=mountainArr.get(m+1);
            if(m_val<m_r_val)
                l=m+1;
            else
                r=m-1;
        }
        return l;
    }
    int findInMountainArray(int target, MountainArray &mountainArr)
    {
        int peak=find_peak(mountainArr);
        int l=0, r=peak;
        if(mountainArr.get(l)<=target&&mountainArr.get(r)>=target)
            while(l<=r)
            {
                int m=(l+r)/2;
                int val=mountainArr.get(m);
                if(val==target)
                    return m;
                else if(val<target)
                    l=m+1;
                else
                    r=m-1;
            }
        l=peak;
        r=mountainArr.length()-1;
        if(mountainArr.get(r)<=target&&mountainArr.get(l)>=target)
            while(l<=r)
            {
                int m=(l+r)/2;
                int val=mountainArr.get(m);
                if(val==target)
                    return m;
                else if(val<target)
                    r=m-1;
                else
                    l=m+1;
            }
        return -1;
    }
};

 

posted on 2019-06-23 12:23  JASONlee3  阅读(162)  评论(0编辑  收藏  举报

导航