美文网首页
154. Find Minimum in Rotated Sor

154. Find Minimum in Rotated Sor

作者: 留十夜 | 来源:发表于2017-08-03 15:02 被阅读0次

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

    Would this affect the run-time complexity? How and why?
    Suppose an array sorted in ascending order 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


    仍然是在旋转有序数组中查找最小值,但是此时元素允许重复。有可能遇到如图所示的情况。

    此时无法继续判断,只能退回到线性遍历的方式。

    //顺序遍历辅助函数
    int help(vector<int> &num,int start,int end){
            int min_v = num[start];
            for(int i=start+1;i<=end;i++){
                min_v = min(min_v,num[i]);
            }
            return min_v;
        }
        
        int findMin(vector<int> &num) {
            int start=0,end=num.size()-1;
            
            while (start<end) {
                if (num[start]<num[end])
                    return num[start];
                
                int mid = (start+end)/2;
                
                if(num[mid]==num[start] && num[mid]==num[end]){
                    return help(num,start,end);
                }
                
                if (num[mid]>=num[start]) {
                    start = mid+1;
                } else {
                    end = mid;
                }
            }
            
            return num[start];
        }
    

    相关文章

      网友评论

          本文标题:154. Find Minimum in Rotated Sor

          本文链接:https://www.haomeiwen.com/subject/xhsplxtx.html