题目要求如下:
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.
You may assume no duplicate exists in the array.
本题就是寻找轴,或者说最小值。。也有其他几道涉及rotated array的问题应该都跟找到pivot有关。。
本题最直观的方法就是brute force,直接遍历一遍array,看看哪个num[i] < num[i-1],就是解。。很神奇的是,即便这样,也能通过测试。。。不过这么丧心病狂的方法显然不能跟面试官讲。。。而且并没有用到sorted array的性质。。。
本题我用类似二分查找的方式解决的,代码如下所示:
class Solution {
public:
int findMin(vector<int> &num) {
/* find the pivot */
int low = 0;
int high = num.size()-1;
while (num[low] > num[high]) {
int mid = (low + high) / 2;
if (num[mid] >= num[low]) {
low = mid + 1;
}
else {
/* can't discard mid val, so test again in the next iteration */
high = mid;
}
}
return num[low];
}
};
基本思路:
1,最外层循环,如果num[low]>num[high],说明pivot还没有找到,继续循环,如果num[low] <= num[high]说明已经找到,跳出循环,返回num[low]
2,循环内:设一个中点,如果num[mid]>=num[low],则说明pivot必然不在其中,需要寻找array的后半段;反之,则需要寻找array的前一半。这样每次把寻找范围缩小一半,故时间复杂度是O(log(n))。