題目來源
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 duplicates.
一開始做的題目呢刹前,是沒有重復的數(shù)組叠赐,用直接遍歷的話顯然是不行的阱缓,會超時宜肉。那就二分查找吧吟温,這個想法也很自然嗯嗯。不考慮重復元素的話直接如下就下可以了梅鹦。因為沒有重復元素裆甩,所以當nums[mid] == nums[l]
的時候,實際上就相當于mid == l
齐唆。
class Solution {
public:
int findMin(vector<int>& nums) {
int n = nums.size();
int l = 0, r = n - 1, mid = 0;
while (l < r) {
if (nums[l] < nums[r])
return nums[l];
mid = (l + r) / 2;
if (nums[mid] >= nums[l])
l = mid + 1;
else
r = mid;
}
return nums[l];
}
};
假如數(shù)組中存在重復元素的話嗤栓,那么對于nums[mid] == nums[l]
的情況呢,我是直接把l
加1。反正l
加1之后最小值肯定還是在l
到r
之間的茉帅,代碼如下:
class Solution {
public:
int findMin(vector<int>& nums) {
int n = nums.size();
int l = 0, r = n - 1, mid = 0;
while (l < r) {
if (nums[l] < nums[r])
return nums[l];
mid = (l + r) / 2;
if (nums[mid] > nums[l])
l = mid + 1;
else if (nums[mid] == nums[l])
l = l + 1;
else
r = mid;
}
return nums[l];
}
};