[leetcode_153]Find Minimum in Rotated Sorted Array

This is an interesting problem. Given a sorted array: 1,2,3,4,5,6,7, but it has been rotated, for example: 4,5,6,7,1,2,3. The task is to find the minimum element. An O(n) solution is always possible. I remember being asked a similar question during a Didi interview last year. I was sure it was binary search at the time, but felt I didn’t explain it clearly. This time, the approach is much clearer.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
    void binarySearch(vector<int>& nums, int left, int right, int &min)
    {
        if (left > right)
        {
            return ;
        }
        int mid = (left + right) / 2;
        if (nums[mid] >= min)
        {
            binarySearch(nums, left, mid - 1, min);
            binarySearch(nums, mid+1, right, min);
        }
        else
        {
            min = nums[mid];
            binarySearch(nums, left, mid - 1, min);
        }
    }

    int findMin(vector<int>& nums) {
        int min = nums[0];
        binarySearch(nums, 0, nums.size() - 1, min);
        return min;
    }
};