【LeetCode】153. Find Minimum in Rotated Sorted Array (3 solutions)

时间:2021-04-29 04:56:18

Find Minimum in Rotated Sorted Array

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.

Search in Rotated Sorted Array,Search in Rotated Sorted Array II,Find Minimum in Rotated Sorted Array II对照看

解法一:暴力解法,直接使用algorithm库中的求最小元素函数

需要遍历整个vector

class Solution {
public:
int findMin(vector<int> &num) {
if(num.empty())
return ;
vector<int>::iterator iter = min_element(num.begin(), num.end());
return *iter;
}
};

【LeetCode】153. Find Minimum in Rotated Sorted Array (3 solutions)

解法二:利用sorted这个信息。如果平移过,则会出现一个gap,也就是从最大元素到最小元素的跳转。如果没有跳转,则说明没有平移。

比上个解法可以省掉不少时间,平均情况下不用遍历vector了。

class Solution {
public:
int findMin(vector<int> &num) {
if(num.empty())
return ;
else if(num.size() == )
return num[];
else
{
for(vector<int>::size_type st = ; st < num.size(); st ++)
{
if(num[st-] > num[st])
return num[st];
}
return num[];
}
}
};

【LeetCode】153. Find Minimum in Rotated Sorted Array (3 solutions)

解法三:二分查找

Search in Rotated Sorted Array对照来看

Search in Rotated Sorted Array题中是二分查找最大值,而本题是二分查找最小值。

class Solution {
public:
int findMin(vector<int>& nums) {
if(nums.empty())
return ;
if(nums.size() == )
return nums[];
int n = nums.size();
int low = ;
int high = n-;
while(low < high && nums[low] > nums[high])
{
int mid = low + (high-low)/;
if(nums[mid] < nums[low]) // mid is in second part
high = mid;
else if(nums[mid] == nums[low]) // since (low<high)-->(low+1==high)
return nums[high]; // nums[low]>nums[high]
else
low = mid+;
}
return nums[low];
}
};

【LeetCode】153. Find Minimum in Rotated Sorted Array (3 solutions)