Cpp solutions, complexity O(n)


  • 0
    P

    Since there exists the worst cases that: {1,1,...,1,0,1,...,1}, the complexity has to be O(n). Then the most easy way is using a linear search:

    int min_num = nums[0];
    for(int i=1;i<nums.size();i++)  min_num = min(min_num,nums[i]);
    return min_num;
    

    However, we can improve it by removing the duplicates on both sides and doing a bi-section search similar as the last problem:

    class Solution {
    public:
        int findMin(vector<int>& nums) {
            int left = 0, right = nums.size()-1;
            if(nums[left]<nums[right]) return nums[left];
            while(left<right && nums[left+1]==nums[left]) left++;
            while(right>left && nums[right-1]==nums[right]) right--;
            while(right>left+1){
                int c = (right+left)/2;
                if(nums[c]>= nums[left]) left = c;
                else right = c;
            }
            return nums[right];
        }
    };
    

    Both running time is 8 ms.


Log in to reply
 

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