class Solution {
public:
int forward(vector<int>& nums, int target)
{
int max = nums.at(0);
for(int i=0;i<nums.size();i++)
{
if(nums.at(i)>=max)
{
max = nums.at(i);
if(nums.at(i) == target)
return i;
}
else
return -1;
}
return -1;
}
int backward(vector<int>& nums, int target)
{
int size = nums.size();
int max = nums.at(size-1);
for(int i=size-1;i>=0;i--)
{
if(nums.at(i)<=max)
{
max = nums.at(i);
if(nums.at(i) == target)
return i;
}
else
return -1;
}
return -1;
}
int search(vector<int>& nums, int target)
{
if(nums.size() == 0)
return -1;
if(nums.size() == 1)
{
if(nums.at(0) == target)
return 0;
else
return -1;
}
if(target < nums.at(0))
return backward(nums,target);
else
return forward(nums,target);
}
};
LeetCode 33. 搜索旋转排序数组
于 2022-03-27 23:51:41 首次发布