题目链接:33. 搜索旋转排序数组 - 力扣(LeetCode)
class Solution {
public:int search(vector<int>& nums, int target) {int n = (int)nums.size();if(!n){return -1;}if(n == 1){return nums[0] == target ? 0 : -1;}int left = 0, right = nums.size() - 1;while(left <= right){int mid = left + (right - left) / 2;if(nums[mid] == target) return mid;if(nums[0] <= nums[mid]){if(nums[0] <= target && target < nums[mid]){right = mid - 1;}else{left = mid + 1;}}else{if(nums.back() >= target && target > nums[mid]){left = mid + 1;} else{right = mid - 1;}}}return -1;}
};
这个题目也算是看着力扣官方给的题解写的,我在这里再给我自己解释一下,首先看到这题目,我们首先应该想到的是把旋转后的数组分为两部分,一部分是有序,一部分是无序。
要说的话都在图片里面了