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

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)