Binary Search Solution C++


  • 0
    S

    class Solution {
    public:
    int findMin(vector<int> &num) {
    if (num.size() == 0) {
    return -1;
    }

        int start = 0;
        int end = (int)num.size() - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (num[mid] < num[mid - 1] && num[mid] < num[mid + 1]) {
                return num[mid];
            } else if ((num[start] < num[mid]) && num[mid] < num[end]) {
                end = mid;
            } else if (num[start] < num[mid]) {
                start = mid;
            } else if (num[mid] < num[end]) {
                end = mid;
            }
            
        }
        
        if (num[start] < num[end]) {
            return num[start];
        } else {
            return num[end];
        }
        
    }
    

    };


  • 0
    S

    Nice solution. Thanks for sharing


  • 0
    S

    i think it is better put below code into before while loop.
    if (num[start] < num[end])
    return num[start];


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.