153题目:
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.
这个题不知道O(n)能不能过,但既然出出来了,那就肯定不是那种暴力的方法。
因为只有一次rotate,(假设rotate后不是单调升),所以除了某两个数之间其他都是有序的。
所以,相当于有两段上升的序列,且前一段的最小值比后一段的最大值要大。
然后依据这个特点二分求解即可。
class Solution {
public:
int findMin(vector<int>& nums) {
return find(nums, 0, nums.size() - 1);
}
int find(vector<int>& nums, int lt, int rt) {
if (lt == rt) return nums[lt];
if (lt + 1 == rt) return min(nums[lt], nums[rt]);
int mid = (lt + rt) >> 1;
if (nums[lt] > nums[rt]) {
if (nums[mid] > nums[rt]) return find(nums, mid, rt);
else return find(nums, lt, mid);
}
else return nums[lt];
}
};
154题目:
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.
这个题允许重复数字。
所以,我认为这个题是做不到logn复杂度的,比如说:1,1,1……1,2,-1,1,1,1…..1
最小的数字是-1,但是两侧有很多很多1,所以二分的时候mid的值也是1,所以无法判断是在哪个区间。
所以只能将左边界右移一位(或者右边界左移一位),这样,算法就是O(N)复杂度了。
但是呢,这样写也是能过的。
总而言之,个人认为这个题没有任何意义。
class Solution {
public:
int findMin(vector<int>& nums) {
return find(nums, 0, nums.size() - 1);
}
int find(vector<int>& nums, int lt, int rt) {
if (lt == rt) return nums[lt];
if (lt + 1 == rt) return min(nums[lt], nums[rt]);
int mid = (lt + rt) >> 1;
if (nums[lt] > nums[rt]) {
if (nums[mid] > nums[rt]) return find(nums, mid, rt);
else return find(nums, lt, mid);
}
else if (nums[lt] < nums[rt]) return nums[lt];
else return find(nums, lt + 1, rt);
}
};