Two C++ solutions - STL approach and Binary Search approach


  • 1
    P

    First, using STL:

        int findMin(vector<int>& nums) {
            auto it = std::is_sorted_until(nums.begin(), nums.end());
            if(it == nums.end()) return nums[0];
            else                 return *it;
        }
    

    Next, a modified binary search approach:

    int findMin(vector<int>& nums) {
       int b = 0;
       /* Create an iterative loop (similar to binary search) */
       for(int e = nums.size() - 1; b < e && nums[b] > nums[e]; ) {
          int m = b + (e - b) / 2;       /* calc mid point   */
          if(nums[m] < nums[e]) e = m;   /* go to left half  */
          else                  b = m+1; /* go to right half */
       }
       return nums[b];
    }
    

Log in to reply
 

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