简体   繁体   English

在二进制搜索主题下的 InterviewBit 问题中的 C++ 中的旋转排序数组中的搜索超出了时间限制

[英]Time Limit Exceeded for search in rotated sorted array in C++ in InterviewBit problem under topic Binary Search

The problem is to search for an element in a sorted, rotated array in C++. The approach that I have used is to find the pivot element index/ the minimum element index and then to find the key either from a[pivot......end] or a[beg,....pivot] use binary search.问题是在 C++ 中的排序旋转数组中搜索元素。我使用的方法是找到 pivot 元素索引/最小元素索引,然后从 [pivot.... ..end] 或 a[beg,....pivot] 使用二进制搜索。

The time complexity to find the minimum element index is O(log n) and then for finding the element is also O(log n) and hence the overall time complexity will be O(log n)找到最小元素索引的时间复杂度是 O(log n) 然后找到元素也是 O(log n) 因此整体时间复杂度将是 O(log n)

But I am getting Time Limit Exceeded error Here is my code:但是我收到超出时间限制的错误这是我的代码:

int find_pivot(std::vector<int> a, int beg, int end)
{
    while(beg<=end)
    {
        int mid=(beg+end)/2;
        if(mid>0 && a[mid]<a[mid-1])
            return mid;
        else if(a[mid]>a[end])
            beg=mid+1;
        else
            end=mid;
    }
}

int search_element(std::vector<int> a, int key, int beg, int end)
{
    int pivot = find_pivot(a,0,a.size()-1);
    if(key>=a[pivot] && key<=a[end])
        beg=pivot;
    else
        end=pivot;
    while(beg<=end)
    {
        int mid=(beg+end)/2;
        if(key==a[mid])
            return mid;
        else if(key>a[mid])
            beg=mid+1;
        else
            end=mid-1;
    }
    return -1;
}

int Solution::search(const vector<int> &A, int B) {
    int n = A.size();
   int i = search_element(A, B, 0, n-1); 

    if (i != -1) 
    return i;
    else
    return -1;
}

Check your find_pivot function, Lets say array is normally sorted [1,2,3,4,5].检查你的 find_pivot function,假设数组通常排序为 [1,2,3,4,5]。 Now when you call your find_pivot function, there will come a time when beg=0 and end =1.现在,当您调用 find_pivot function 时,会出现 beg=0 和 end =1 的时间。

Now, since mid=(beg+end/2)=0 your function will change end=mid which means end also becomes 0.现在,由于 mid=(beg+end/2)=0 你的 function 将改变 end=mid 这意味着 end 也变为 0。

Now your beg=0 and end=0, now when the loop starts again Mid = 0+0/2 and and this will keep on repeating.现在你的 beg=0 和 end=0,现在当循环再次开始时 Mid = 0+0/2 并且这将继续重复。

Make some changes and I think the issue is when the array is normally sorted or when end=begin.进行一些更改,我认为问题出在数组正常排序时或 end=begin 时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM