整数数组 nums 按升序排列,数组中的值 互不相同 。
在传递给函数之前,nums 在预先未知的某个下标 k(0 <= k < nums.length)上进行了 旋转,使数组变为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下标 从 0 开始 计数)。例如, [0,1,2,4,5,6,7] 在下标 3 处经旋转后可能变为 [4,5,6,7,0,1,2] 。
给你 旋转后 的数组 nums 和一个整数 target ,如果 nums 中存在这个目标值 target ,则返回它的下标,否则返回 -1 。
示例 1:
输入:nums = [4,5,6,7,0,1,2], target = 0
输出:4
示例 2:
输入:nums = [4,5,6,7,0,1,2], target = 3
输出:-1
示例 3:
输入:nums = [1], target = 0
输出:-1
提示:
1 <= nums.length <= 5000
-10^4 <= nums[i] <= 10^4
nums 中的每个值都 独一无二
题目数据保证 nums 在预先未知的某个下标上进行了旋转
-10^4 <= target <= 10^4
题解一(暴力解法):
class Solution {
public:
int search(vector<int>& nums, int target) {
auto it = nums.rbegin();
if (target == *it)
{
return nums.size() - 1;
}
else if (target < *it)
{
int index = nums.size() - 1;
while (it != nums.rend())
{
if (*it == target)
{
return index;
}
index--;
it++;
}
}
else
{
auto it = nums.begin();
int index = 0;
while (it!=nums.end())
{
if (*it == target)return index;
index++;
it++;
}
}
return -1;
}
};
题解二(二分查找,时间复杂度O(logn)):
class Solution {
public:
int search(vector<int>& nums, int target) {
return binsea(nums, 0, nums.size() - 1, target);
}
int binsea(vector<int> nums, int l, int r,int target)
{
int mid = (l + r) / 2;
if (l > r)return -1;
if (nums[l] == target)return l;
else if (nums[r] == target)return r;
else if (nums[mid] == target)return mid;
if (nums[l] < nums[mid])//左边有序
{
if (nums[mid] >= target&&nums[l]<=target)return binsea(nums, l, mid - 1, target);
else return binsea(nums, mid + 1, r, target);
}
else//右边有序
{
if (nums[mid] <= target&&nums[r]>=target)return binsea(nums, mid + 1, r, target);
else return binsea(nums, l, mid - 1, target);
}
}
};
class Solution {
public:
int search(vector<int>& nums, int target) {
int l = 0;
int r = nums.size() - 1;
int mid;
if (nums[l] == target)return l;
else if (nums[r] == target)return r;
if (r == 0)return nums[0] == target ? 0 : -1;
while (l <= r)
{
mid = (l + r) / 2;
if (nums[mid] == target)return mid;
if (nums[l] <= nums[mid])//左边数组有序
{
if (nums[mid] > target && nums[l] <= target)r = mid - 1;
else l = mid + 1;
}
else
{
if (nums[mid] < target && nums[r] >= target)l = mid + 1;
else r = mid - 1;
}
}
return -1;
}
};
上述代码进入测试后出现问题,问题出在nums[l]<nums[mid]没有加等号,即应该是<=,但具体为什么我也不知道呃呃,但是我在评论区找到答案了: