Easy C++ solution in 6ms, beats 100%


  • 0
    M
    class Solution {
    public:
        int findMin(vector<int>& nums) {
            int left = 0, right = nums.size()-1;
            while (left <= right) {
                if (left == right) {
                    return nums[left];
                }
                else {
                    int mid = left + (right - left) / 2;
                    if (mid + 1 < nums.size() && nums[mid] > nums[mid+1]) {
                        return nums[mid+1];
                    }
                    else {
                        //if left part is messed up:
                        if (nums[left] > nums[mid]) {
                            right = mid;
                        }
                        //if the right part is messed up:
                        else if (nums[mid] > nums[right]) {
                            left = mid + 1;
                        }
                        //if encounter duplicates:
                        else if ((left!=mid && nums[mid] == nums[left]) || (mid!=right &&nums[mid] == nums[right])) {
                            left = (left != mid && nums[mid] == nums[left]) ? left + 1 : left;
                            right = (mid != right &&nums[mid] == nums[right]) ? right - 1 : right;
                        }
                        //the (sub)array is not messed up at all:
                        else {
                            return nums[left];
                        }
                    }
                }
            }
            return nums[0];
        }
    };
    

Log in to reply
 

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