您的位置:首页 > 其它

leetcode题目 旋转排序数列的查找

2015-10-05 18:03 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.

思路: 普通的二分查找只有两种情况,而旋转数列的查找则有6种情况,分情况移动前后指针即可。当然,递归也可以实现。

class Solution {
public:
int search(vector<int>& nums, int target) {
int fir=0;
int sec=nums.size()-1;
int mid=0;
bool Isfront=false;
if(target>=nums[0])
Isfront=true;
while(fir>=0&&sec>=0&&fir<nums.size()&&sec<nums.size()&&fir<=sec)
{
mid=(fir+sec)/2;
if(nums[mid]>=nums[0])
{
if(nums[mid]<target)
{
fir=mid+1;
continue;
}
else if(nums[mid]>target)
{
if (Isfront)
{
sec = mid - 1;
continue;
}
else
{
fir = mid + 1;
continue;
}
}
else
return mid;
}
else
{
if(nums[mid]<target)
{
if(Isfront)
{
sec=mid-1;
continue;
}
else
{
fir=mid+1;
continue;
}

}
else if(nums[mid]>target)
{
sec=mid-1;
continue;
}
else
return mid;
}
}
return -1;
}
};


运行时间4ms,测试结果虽然只击败了12%的代码,但是看到大家都集中在4ms附近。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: