153 Find Minimum in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element. You may assume no duplicate exists in the array.

Solution

class Solution {
public:
    int findMin(vector<int>& nums) {
        int n = nums.size();
        int l = 0, r = n-1;
        while ( l < r-1 ) {
            int m = (l+r)/2;
            if ( nums[l] < nums[m] and nums[m] < nums[r] ) return nums[l];
            if ( nums[l] > nums[m] ) { r = m; continue;}
            if ( nums[m] > nums[r] ) { l = m; continue;}
        }
        return min(nums[l], nums[r]);
    }
};

Duplicate allowed?
Solution
remember to skip the consecutive "same numbers".

class Solution {
public:
    int findMin(vector<int>& nums) {
        int n = nums.size();
        int l = 0, r = n-1, m;
        while ( l < n-1 and nums[l] == nums[l+1] ) l += 1;
        if ( l == n-1 ) return nums[l];
        while ( r > 0 and nums[r] == nums[r-1] ) r--;
        while ( l < r-1 ) {
            m = (l+r)/2;
            if ( nums[l] < nums[m] and nums[m] < nums[r] ) return nums[l];
            if ( nums[l] > nums[m] ) {
                r = m;
                while ( r > l and nums[r] == nums[r-1] ) r--;
                continue;
            }
            if ( nums[m] > nums[r] ) {
                l = m;
                while ( l < r and nums[l] == nums[l+1] ) l++;
                continue;
            }
        }
        return min(nums[l], nums[r]);
    }
};

results matching ""

    No results matching ""