class Solution { public: int search(vector<int>& nums, int target) { //这个题是给一个排序数组,但是数组里面内容被平行移动了,现在要找到tagert所对应的下标 int len = nums.size(); //特殊情况先考虑掉 if (len == 0) { return -1; } if (len == 1 && target != nums[0]) { return -1; } //正常情况,应该不能遍历一边数组吧,这样没有意义,应该也无法通过;虽然顺序被打乱了,但是部分还是有序的,我们还是使用二分查找 int left = 0; int right = len - 1; int mid = 0; while (left <= right) { mid = left + (right - left) / 2; if (target == nums[left]) { return left; } if (target == nums[right]) { return right; } if (target == nums[mid]) { return mid; } //二分查找 if (nums[mid] >= nums[left]) {//左边有序 if (target > nums[left] && target < nums[mid]) { right = mid - 1; } else { left = mid + 1; } } else {//右边有序 if (target > nums[mid] && target < nums[right]) { left = mid + 1; } else { right = mid - 1; } } } return -1; } };