zoukankan      html  css  js  c++  java
  • LeetCode OJ--Search in Rotated Sorted Array II

    http://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/

    如果在数组中有重复的元素,则不一定说必定前面或者后面的一半是有序的,所以有个while循环的处理。

    #include <iostream>
    using namespace std;
      
    class Solution {
    public:
        bool binarySearch(int A[],int target,int begin,int end)
        {
            int mid = (begin+end)/2;
    
            if(target == A[mid])
                return true;
            if(target == A[begin])
                return true;
            if(target == A[end])
                return true;
            if(begin>=end)
                return false;
    
            while(A[begin] == A[mid])
                begin++;
            if(A[begin]<A[mid])//前面有序
            {
                if(target>A[begin] && target<A[mid]) //在前面
                    return binarySearch(A,target,begin,mid-1);
                else
                    return binarySearch(A,target,mid+1,end); //在后面
            }
            else if(A[mid]<=A[end])//后面有序
            {
                while(A[mid] == A[end])
                    end--;
                if(target>A[mid] && target<A[end]) //在后面
                    return binarySearch(A,target,mid+1,end);
                else
                    return binarySearch(A,target,begin,mid-1);//在前面
            }
            return false;
        }
        bool search(int A[], int n, int target) {
           return  binarySearch(A,target,0,n-1);
        }
    };
    
    int main() 
    {
        Solution myS;
    
        int A[] = {1,3,1,1,1};
        bool ans = myS.search(A,5,3);
        cout<<ans<<endl;
        return 0;
    
    }
  • 相关阅读:
    博弈论嘻嘻
    cf之kmp匹配稍稍改一改
    点分治开始!
    后缀数组
    cf之 前缀和差分
    AJAX 数据库实例
    常用jar包用途
    cxf客户端所需最少jar包
    Dbutis
    dbutils入门
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3546363.html
Copyright © 2011-2022 走看看