Find Minimum in Rotated Sorted Array II -- leetcode

Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

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.

The array may contain duplicates.

简译:寻找循环有序数组的最小值,可能存在重复的值。

题目源址


class Solution {
public:
    int _findMin(vector<int> &num, int low, int high) {
        if (low == high || num[low] < num[high])
                return num[low];

        const int mid = low + (high-low)/2;

        if (num[low] == num[mid] && num[mid] == num[high]) {
                const int left = _findMin(num, low, mid);
                if (left < num[mid])
                        return left;
                else
                        return _findMin(num, mid+1, high);
        }

        if (num[mid] <= num[high])
                return _findMin(num, low, mid);
        else
                return _findMin(num, mid+1, high);
    }

    int findMin(vector<int> &num) {
        return _findMin(num, 0, num.size()-1);
    }
};


本算法是在参考下面博客后完成的。个人感觉比他的要高效一些。

Find the minimum element in a sorted and rotated array


附上他的代码,供对照。

// The function that handles duplicates.  It can be O(n) in worst case.
int findMin(int arr[], int low, int high)
{
    // This condition is needed to handle the case when array is not
    // rotated at all
    if (high < low)  return arr[0];
 
    // If there is only one element left
    if (high == low) return arr[low];
 
    // Find mid
    int mid = low + (high - low)/2; /*(low + high)/2;*/
 
    // Check if element (mid+1) is minimum element. Consider
    // the cases like {1, 1, 0, 1}
    if (mid < high && arr[mid+1] < arr[mid])
       return arr[mid+1];
 
    // This case causes O(n) time
    if (arr[low] == arr[mid] && arr[high] == arr[mid])
        return min(findMin(arr, low, mid-1), findMin(arr, mid+1, high));
 
    // Check if mid itself is minimum element
    if (mid > low && arr[mid] < arr[mid - 1])
       return arr[mid];
 
    // Decide whether we need to go to left half or right half
    if (arr[high] > arr[mid])
       return findMin(arr, low, mid-1);
    return findMin(arr, mid+1, high);


算法改进处:
在low, mid, high三点处值相等时,其实不一定非要,两个区间都进行查找。

当在第一个区间已经找到最小值是,第二个区间的查找是可以省掉的。

即,如果第一个区间返回的值,小于mid处的值时,那它一定是最小值。并且第二个区的值一定全部相等。


算法其他区别,见前一篇文档:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值