码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_33题——Search in Rotated Sorted Array(二分查找)

时间:2015-06-22 11:04:32      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

Search in Rotated Sorted Array

 Total Accepted: 57605 Total Submissions: 199639My Submissions

 

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.

 

Hide Tags
 Array Binary Search
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

       这道题需要查找一个特殊的顺序表,这是一个正常的顺序表某个地方发生了一个旋转,再查找,还是使用二分查找,只不过其中需要注意一些问题。

#include<iostream>
#include<vector>
using namespace std;

//正常顺序的查找
int searched(vector<int>& nums,int target,int i,int j)
{
	if(i+1==j)
	{
		if(target==nums[i])
			return i;
		if(target==nums[j])
			return j;
		return -1;
	}
	if(i==j)
	{
		if(target!=nums[i])
			return -1;
		else
			return i;
	}
	if(target<nums[i]||target>nums[j])
		return -1;
	int k=(i+j)/2;
	while(1)
	{
		if(target==nums[k])
			return k;
		if(target>nums[k])
			i=k;
		else
			j=k;
		if(i+1==j)
	{
		if(target==nums[i])
			return i;
		if(target==nums[j])
			return j;
		return -1;
	}
		if(i==j)
		{
			if(target==nums[i])
				return i;
			else
				return -1;
		}
		k=(i+j)/2;
	}
}
//中间不知哪里发生旋转而产生的查找
int search(vector<int>& nums, int target) {
	int len=nums.size();
	int i=0;
	int j=len-1;
	while(1)
	{
	if(i+1==j)
	{
		if(target==nums[i])
			return i;
		if(target==nums[j])
			return j;
		return -1;
	}
		if(i==j)
		{
			if(nums[i]==target)
				return i;
			else
				return -1;
		}
		if(nums[i]<=nums[j])
			return searched(nums,target,i,j);
	
		int k=(i+j)/2;
		if(target==nums[k])
			return k;
		if(nums[i]<=nums[k])
		{
			int last=searched(nums,target,i,k);
			if(last!=-1)
			{return last;}
			i=k;
		}
		if(nums[k]<=nums[j])
		{
			int last=searched(nums,target,k,j);
			if(last!=-1)
				return last;
			j=k;
		}
	}

}
int main()
{
	vector<int> vec;
	vec.push_back(4);vec.push_back(5);vec.push_back(6);vec.push_back(7);vec.push_back(0);vec.push_back(1);
	vec.push_back(2);
	cout<<searched(vec,2,4,6)<<endl;
	cout<<search(vec,2)<<endl;
}

  

leetcode_33题——Search in Rotated Sorted Array(二分查找)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4592999.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!