- Search in Rotated Sorted Array My Submissions Question
Total Accepted: 92936 Total Submissions: 310089 Difficulty: Hard
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.
Subscribe to see which companies asked this question
还是改了挺久的,二分查找的变形,数组边界处理要注意,判断条件也要注意
class Solution {
public:
int search(vector<int>& nums, int target) {
int first=0;
int last=nums.size();
int mid=(last+first)/2;
while(first!=last){
if(nums[mid]==target){
return mid;
}
else if(nums[first]<=nums[mid]){
if(nums[first]<=target && nums[mid]>target){
last=mid;
mid=(last+first)/2;
}
else{
first=mid+1;
mid=(last+first)/2;
}
}
else{
if(nums[last-1]>=target && nums[mid]<target){
//之前一直wa的原因,nums[last]用作判断,越界
first=mid+1;
mid=(last+first)/2;
}
else{
last=mid;
mid=(last+first)/2;
}
}
}
return -1;
}
};