class Solution { public: int search(vector<int>& nums, int target) { int beg = 0; int end = nums.size()-1; while(beg <= end) { int mid = beg + (end-beg)/2; //找到就直接返回 if(target == nums[mid]) return mid; else if( target < nums[mid]) { if(nums[beg] < nums[mid])//[beg, mid]是递增区间 [mid+1, end]包含了旋转区间 { if(target >= nums[beg]) // 递增区间 直接用二分就可以了 { end = mid -1; }// 表明可能在后面的旋转区间里面 else { beg = mid +1; } } else if(nums[beg] > nums[mid]) //[beg, mid]是旋转区间 [mid+1, end]包含了递增区间 { end = mid -1; }//前提是 target < nums[mid] 仅当还剩下两个数的时候,就相当于是target < nums[beg] 因此应该 else if(nums[beg] == nums[mid]) { beg = mid+1; } }// else if(target > nums[mid]) { if(nums[beg] < nums[mid])//[beg,mid]是递增区间,[mid+1, end]包含了旋转区间 { beg = mid+1; } else if(nums[beg] > nums[mid])//前面是旋转区间,后面是递增区间, { if(target >= nums[beg])//nums[beg] > nums[end] { end = mid -1; } else { beg = mid +1; } }// 如果仅仅剩下两个元素了,target > nums[mid] else if(nums[beg] == nums[mid]) { beg = mid +1; } } } return -1; } };
原文地址:https://www.cnblogs.com/randyniu/p/9354097.html
时间: 2024-10-09 16:34:52