首页 > 代码库 > 033. Search in Rotated Sorted Array

033. Search in Rotated Sorted Array

 1 class Solution { 2 public: 3     int search(vector<int>& nums, int target) { 4         if (nums.size() == 0) return -1; 5         else { 6             int left = 0, right = nums.size() - 1; 7             while (left <= right) { 8                 int mid = left + (right - left) / 2; 9                 //cout << "left = " << left << ‘\t‘ << "right = " << right << endl;10                 if (nums[mid] == target) return mid;11                 else if (nums[mid] < target) {12                     if (nums[mid] < nums[right]) {13                         if (nums[right] == target) return right;14                         else if (nums[right] < target) right = mid - 1;15                         else left = mid + 1;16                     }17                     else {18                         left = mid + 1;19                     }20                 }21                 else {22                     if (nums[mid] < nums[right]) right = mid - 1;23                     else {24                         if (nums[left] == target) return left;25                         else if (nums[left] < target) right = mid - 1;26                         else  left = mid + 1;27                     }28                 }29             }30             return -1;31         }32     }33 };

 

033. Search in Rotated Sorted Array