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;
}
相關文章
相關標籤/搜索