【题目】
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.
You may assume no duplicate exists in the array.
【题解】
本题有两种做法:
1、由于数组是在排好序后旋转的,故只需从头到尾扫描一次,若当前的元素比前次的元素小时,便找到了最小的元素,时间复杂度为O(n)
2、另一种做法是使用改版的二分查找,当中间的元素小于当前循环最右边的元素时,最右边的边界设置为中间元素的索引;当间的元素大于当前循环最右边的元素时,最左边的边界设置为中间元素的索引加1。循环的条件是最左边的元素大于最右边的元素,时间复杂度为O(lgn)
【代码】
O(n)算法:
int findMin(vector<int>& nums) {
int nResult = nums[0];
int nSize = nums.size();
int nPre = nums[0];
for (int i = 1; i < nSize; i++) {
if (nums[i] < nPre) {
nResult = nums[i];
break;
}
nPre = nums[i];
}
return nResult;
}
O(lgn)算法:
int findMin(vector<int>& nums) {
int nSize = nums.size();
if (nSize == 1)
return nums[0];
int nLeft = 0;
int nRight = nSize - 1;
while (nums[nLeft] > nums[nRight]) {
int nMid = (nLeft + nRight)/2;
if (nums[nMid] < nums[nRight])
nRight = nMid;
else
nLeft = nMid + 1;
}
return nums[nLeft];
}