I think the test cases can be harder, and my solution is better in extreme cases!


  • 0
    P

    It stops earlier in linear search!

    int findMin(vector<int>& nums) {
        int start = 0, end = nums.size()-1, mid;
        while (start <= end) {
            mid = (start+end)/2;
            if (nums[mid] > nums[end]) {
                start = mid + 1;
            } else if (nums[mid] < nums[end]) {
                end = mid;
            } else {
                for (int i = start;i <= end;++i)
                    if (nums[i] > nums[end]) {
                        for (int j = i+1;j <= end;++j)
                            if (nums[j] <= nums[end])
                                return nums[j];
                    } else if (nums[i] < nums[end])
                        return nums[i];
                return nums[end];
            }
        }
        return nums[start];
    }

  • 0
    Q

    I think the bandi's solution is perhaps optimal. I modified the code a little.

    int findMin(vector<int>& nums) {
        int left=0, right=nums.size()-1;
        while(nums[left]>=nums[right] && left<right) {
            int mid=left+((right-left)>>1);
            if(nums[mid]>nums[right]) left=mid+1;
            else if(nums[mid]<nums[right] || nums[mid]!=nums[left]) right=mid;
            else { ++left, --right; }
        }
        return nums[left];
    }

Log in to reply
 

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