4,5,6,7,0,1,2], target = 00 1 2 4 5 6 7
7 0 1 2 4 5 6
6 7 0 1 2 4 5
5 6 7 0 1 2 4
4 5 6 7 0 1 2
2 4 5 6 7 0 1
1 2 4 5 6 7 0
Time Complexity: O(logn)
完整程式碼:
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
while (left <= right) {
// avoid overflow
int mid = left + (right - left) / 2;
if (nums[mid] == target) { return mid; }
// which means that mid ~ right is sorted
if (nums[mid] < nums[right]) {
// target is in this range
if (nums[mid] < target && nums[right] >= target) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
// which means that left ~ mid is sorted
else {
// target is in this range
if (nums[mid] > target && nums[left] <= target) {
right = mid - 1;
}
else {
left = mid + 1;
}
}
}
return -1;
}
};
沒有留言:
張貼留言