旋转数组
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
class Solution { public: int search(vector<int>& nums, int target) { int left = 0; int right = nums.size()-1; int mid = (left+right)/2; if(nums.empty()) return -1; int result = -1; if(nums[mid] == target) return mid; while(left <= right){ //cout << mid << ","; if(nums[mid] == target){ result = mid; break; } if(nums[left] < nums[mid]) { if(nums[left] == target) return left; if(nums[mid] > target && nums[left] < target) { right = mid-1; mid = (right+left)/2; } else { left = mid+1; mid = (left+right) /2; } } else { if(nums[right] == target) return right; if(nums[mid] < target && target <nums[right] ){ left = mid+1; mid = (left+right) / 2; } else { right = mid-1; mid = (left+right) / 2; } } } return result; } };
The Safest Way to Get what you Want is to Try and Deserve What you Want.