Search in Rotated Sorted Array II

Follow up forSearch in Rotated Sorted Array :What if duplicates are allowed?ios

Would this affect the run-time complexity?How and Why?数组

Write a function to determine if a given target is in the array.测试

容许数组旋转,而且还容许数组重复,这种状况下,仍是能够使用二分法来查找目标元素。this

若是容许数组中元素重复,在数组旋转以后,a[m]>=a[1]的状况下,1~m之间的数组就不必定是单调递增的。好比{1,3,1,1,1}. 其实只有等于号的状况下,递增性是不肯定的。那就须要将=和>分开考虑。spa

  • a[m]>a[1],则在[1,m]之间,数组必定是递增的,就算有重复元素,这一段也仍是递增的。
  • a[m]=a[1],在[1,m]之间,数组就不必定是递增的了。那就须要查看下一个元素。

解决方案:.net

class Solution
{
public:
    int search(const vector<int>& num,int target)
    {
        int first = 0;
        int last = num.size();
        while(first != last)
        {
           const int mid = first + (last - first)/2;
           if(num[mid] == target)
               return  mid;
           if(num[first] < num[mid])
           {
               if(num[first] <= target && num[mid] > target)
                   last = mid;
               else
                   first = mid + 1;
           }
            else if(num[first] > num[mid])
           {
               if(num[mid]< target && num[last] > target)
                   first = mid + 1;
               else
                   last = mid;
           }
           else
           {
               first+=1;
           }
        }
        return -1;
    }
};

测试代码:code

#include<iostream>
#include<vector>

using namespace std;


class Solution
{
public:
    int search(const vector<int>& num,int target)
    {
        int first = 0;
        int last = num.size();
        while(first != last)
        {
           const int mid = first + (last - first)/2;
           if(num[mid] == target)
               return  mid;
           if(num[first] < num[mid])
           {
               if(num[first] <= target && num[mid] > target)
                   last = mid;
               else
                   first = mid + 1;
           }
            else if(num[first] > num[mid])
           {
               if(num[mid]< target && num[last] > target)
                   first = mid + 1;
               else
                   last = mid;
           }
           else
           {
               first+=1;
           }
        }
        return -1;
    }
};

int main(void)
{

    vector<int> a;
    int target = 1;

    a.push_back(4);
    a.push_back(5);
    a.push_back(5);
    a.push_back(6);
    a.push_back(6);
    a.push_back(7);
    a.push_back(7);
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);
    a.push_back(4);

    Solution s;
    int result = s.search(a,target);
    cout <<"The"<<" "<<target<<" "<<"is located in "<<result<<endl;
    return 0;
}
相关文章
相关标签/搜索