[LeetCode] Find Minimum in Rotated Sorted Array II

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.

 

Hide Tags
 Array Binary Search
 

 

 

在 http://www.cnblogs.com/diegodu/p/4576831.html 的基础上修改两点:

1.  while(low < high && A[low] > A[high])  --->  while(low < high && A[low] >= A[high]) 因为存在重复元素。。

2、在无重复元素时,中间元素与首元素相等,表示一共只有两个元素,low与high各指向一个。

由于while循环中限制的大小关系,因此返回nums[high]即为最小值。

然而当存在重复元素时,该条件并不能表示一共只有low和high指向的两个元素,

而是说明low指向的元素重复了,因此删除其一,low ++即可。

 

最后为什么返回的是A[low],因为A[low]返回的一直是 包含pivot的下边界,而且low一直在移动。。

一旦出现A[low] < A[high 的情况说明找到了下边界,所以返回A[low],

另外,如果数组是有序的,那么直接返回A[low]

class Solution {
    public:
        int findMin(vector<int>& A)
        {
            int low = 0;
            int high = A.size() - 1;

            int mid = 0;
            // A[low] > A[high] ensure the pivot is between low and high
            while(low < high && A[low] >= A[high])
            {
                mid = (low + high)/2;

                cout << "low\t" << low<< endl;
                cout << "high\t" << high << endl;
                cout << "mid\t" << mid<< endl;

                if(A[low] < A[mid])//pivot is in bottom half, mid can't be lowest
                {
                    low = mid + 1;
                }
                else if(A[low] == A[mid])//duplicates elements, just remove one
                {
                    low ++;
                }
                else //pivot is in first half, mid may be lowest
                {
                    high = mid;
                }
            }

            return A[low];
        }
};

 

posted @ 2015-06-15 15:54  穆穆兔兔  阅读(162)  评论(0编辑  收藏  举报