leetcode_81——Search in Rotated Sorted Array II(二分查找)

Search in Rotated Sorted Array II

  Total Accepted: 38274 Total Submissions: 121824My Submissions

 

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is 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;



#define TRUE 1

#define FALSE 0



//标准的二分查找

bool searched(vector<int>& nums,int target,int i,int j)

{

	int k;

	while(1)

	{

		if(nums[i]==nums[j])

		{

			if(nums[i]==target)

				return TRUE;

			else

				return FALSE;

		}

		if(i+1==j)

		{

			if(target==nums[i]||target==nums[j])

				return TRUE;

			else

				return FALSE;

		}

		if(i==j)

		{

			if(target==nums[i])

				return TRUE;

			else

				return FALSE;

		}

		k=(i+j)/2;

		if(target==nums[k])

			return TRUE;

		if(target>nums[k])

			i=k;

		else

			j=k;

	}

}



//

bool search(vector<int>& nums, int target) {

	int i=0;

	int j=nums.size()-1;

	int k;

	while(1)

	{

		if(i+1==j)

		{

			if(target==nums[i]||target==nums[j])

				return TRUE;

			else

				return FALSE;

		}

		if(i==j)

		{

			if(target==nums[i])

				return TRUE;

			else

				return FALSE;

		}

		k=(i+j)/2;

		if(nums[i]<nums[k])

		{

			bool bo=searched(nums,target,i,k);

			if(bo==TRUE)

				return TRUE;

			i=k;

		}

		else 

		{

			for(int a=i;a<=j;a++)

				if(nums[a]==target)

					return TRUE;

			return FALSE;

		}

	}

}

int main()

{

	vector<int> vec;

}

  

你可能感兴趣的:(LeetCode)