您的位置:首页 > 其它

LeetCode #33 Search in Rotated Sorted Array

2015-08-14 16:31 375 查看
Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e.,
0 1 2 4 5 6 7
might become
4 5 6 7 0 1 2
).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

class Solution {
private:
int find_rotate_index(vector<int>& nums) {
int left = 0, right = nums.size() - 1;
while(left < right){
int mid = (left + right) >> 1;
if(nums[mid] > nums[right])  left = mid + 1;
else right = mid;
}
return left;
}

public:
int search(vector<int>& nums, int target) {
int rotate_index = find_rotate_index(nums);
int left, right, last_index = nums.size() - 1;
if(target > nums[last_index]) {left = 0; right = rotate_index - 1;}
else if(target < nums[last_index]) {left = rotate_index; right = last_index - 1;}
else return last_index;

while(left <= right){
int mid = (left + right) >> 1;
if(nums[mid] < target) left = mid + 1;
else if(nums[mid] > target) right = mid - 1;
else return mid;
}
return -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: