Leetcode 1185 Solution

This article provides solution to leetcode question 1185 (find-in-mountain-array)

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

Solution

/**
 * // This is the MountainArray's API interface.
 * // You should not implement it, or speculate about its implementation
 * class MountainArray {
 *   public:
 *     int get(int index);
 *     int length();
 * };
 */
class Solution {
public:
    int findInMountainArray(int target, MountainArray &arr) {
        int l = 0;
        int r = arr.length() - 1;
        int m;

        while (l <= r)
        {
            m = (l + r) / 2;

            int prev = arr.get(m - 1);
            int curr = arr.get(m);
            int next = arr.get(m + 1);

            if (prev < curr && curr > next)
                break;
            else if (prev < curr && curr < next)
                l = m;
            else if (prev > curr && curr > next)
                r = m;
        }

        int peak = m;

        l = 0;
        r = peak;

        if (arr.get(peak) < target)
            return -1;

        while (l <= r)
        {
            m = (l + r) / 2;

            if (arr.get(m) == target)
                return m;
            else if (arr.get(m) < target)
                l = m + 1;
            else if (arr.get(m) > target)
                r = m - 1;
        }

        l = peak;
        r = arr.length() - 1;

        while (l <= r)
        {
            m = (l + r) / 2;

            if (arr.get(m) == target)
                return m;
            else if (arr.get(m) > target)
                l = m + 1;
            else if (arr.get(m) < target)
                r = m - 1;
        }

        return -1;
    }
};