Search in Rotated Sorted Array II

来源:互联网 发布:幼儿园配餐软件 编辑:程序博客网 时间:2024/05/17 22:40
/* Search in Rotated Sorted Array II出现重复的时候,因为重复的次数无法得知,原数组旋转折叠的位置也无法得知,所以最后折叠的状态也无法得知,所以无法按照Search in Rotated Sorted Array 的判断标准去判断哪部分有序。*/#include <iostream>using namespace std;class Solution{public:    int search_duplicates(int A[], int n, int target)    {        int first = 0, last = n;        while (first != last)        {            int mid = first+(last-first)/2;            if (target == A[mid])                return true;            if (A[first] < A[mid])            {                if (A[first] <= target && target < A[mid])                    last = mid;                else                    first = mid + 1;            }            else if (A[first] > A[mid])            {                if (A[mid] < target && target <= A[last-1])                    first = mid+1;                else                    last = mid -1;            }            else                first++;        }        return false;    }};int main(){    int A[8]={1,1,3,5,1,1,2,2};    int target;    cout<<"input the search number: ";    cin>>target;    Solution solution;    if(solution.search_duplicates(A,8,target))        cout<<"exists";    else        cout<<"not found";    cout<<endl;    return 0;}

这里写图片描述

这里写图片描述

0 0
原创粉丝点击