水题。
class Solution {
public:
int search(vector<int>& nums, int target) {
// empty
if (nums.empty()) {
return -1;
}
// sorted
if (nums[0] < nums[nums.size() - 1]) {
return ssearch(nums, target, 0, nums.size() - 1);
}
// search mid.
int low = 0;
int up = nums.size() - 1;
int mid = (low + up) >> 1;
while(low <= up) {
if (nums[mid] > nums[nums.size() - 1]) low = mid + 1;
else up = mid -1;
mid = (low + up) >> 1;
}
// search result from part1 or part2.
int part1_start_idx = 0;
int part1_end_idx = low - 1;
int part2_start_idx = low;
int part2_end_idx = nums.size() - 1;
if (target >= nums[0]) {
return ssearch(nums, target, part1_start_idx, part1_end_idx);
} else {
return ssearch(nums, target, part2_start_idx, part2_end_idx);
}
}
int ssearch(vector<int> nums, int target, int low, int up) {
int mid = (low + up) >> 1;
while(low <= up) {
if (nums[mid] < target) low = mid + 1;
else up = mid -1;
mid = (low + up) >> 1;
}
if (nums[low] == target) {
return low;
} else {
return -1;
}
}
};