Search in Rotated Sorted Array II(leetcode)

来源:互联网 发布:百度地图网络异常 编辑:程序博客网 时间:2024/05/16 19:05

题目:

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.

题目来源:https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/

解题思路:二分搜索

#include<iostream>#include <vector>using namespace std;bool search(int A[], int n, int target){if(n==0)return false;if(n==1)return A[0]==target;int lo=0,hi=n-1;while(lo<=hi){int mid=lo+((hi-lo)>>1);if(A[mid]==target)return true;if(A[mid]==A[lo] && A[mid]==A[hi])return (search(A+lo+1,mid-lo-1,target) || search(A+mid+1,hi-mid-1,target));if(A[mid]==A[hi])hi=mid-1;else{if(A[mid]<A[hi] && target>A[mid] && target<=A[hi])//顺序的lo=mid+1;else if(A[mid]<A[hi])hi=mid-1;else if(A[mid]>A[lo] && target<A[mid] && target>=A[lo])hi=mid-1;elselo=mid+1;}}return false;}int main()  {  int A[]={3,1,1};bool result=search(A,3,3);    system("pause");      return 0;  }


0 0
原创粉丝点击