2017-07-15 140 views
0

我在一个在线网站上编写代码。在这里,测试你的实现有不同的阶段,即编译,正确性和效率。正确的答案,但效率阶段的运行时错误

我在two pointers上做了一个问题。它的说法是 -

给定n个非负整数a1,a2,...,an, 其中每个代表坐标(i,ai)处的一个点。 绘制'n'个垂直线,使得线i的两个端点处于(i,ai)和(i,0)处。

找到两条线,它们与x轴一起形成一个容器,使得容器包含最多的水。

你的程序应该返回其对应于可容纳

水的最大面积我正确的答案判决,但在舞台上,以检查效率,得到了运行时错误的整数。现在我有两个问题(第一个是第二个) -

1)在所有测试用例中给出正确的答案判断时,它如何产生运行时错误?

2)如果真的是可能的,任何人都可以帮我找错误或可能的原因,这可能发生,我找不到任何不管我怎么想?/

代码 -

int finds(vector<bool> arr){ 
    int i=0; 
    while(arr[i]!=0)i++; 
    return i; 
} 
int finde(vector<bool> arr){ 
    int i=arr.size()-1; 
    while(arr[i]!=0)i--; 
    return i; 
} 
struct st{ 
    int data; 
    int index; 
}; 
int Solution::maxArea(vector<int> &A) { 
    // Do not write main() function. 
    // Do not read input, instead use the arguments to the function. 
    // Do not print the output, instead return values as specified 
    // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details 
    int n=A.size(),ans=0; 
    vector<bool> visited(n,0); 
    int start=0,end=n-1; 
    if(n<=1)return 0; 

    vector<st> arr; 
    st temp; 
    for(int i=0;i<n;i++){ 
     temp.data=A[i]; 
     temp.index=i; 
     arr.push_back(temp); 
    } 
    sort(arr.begin(),arr.end(),[](st a,st b)->bool{return a.data<=b.data;}); 

    for(int i=0;i<n-1;i++){ 
     // cout<<start<<"\t"<<end<<endl; 
     ans=max(ans,arr[i].data*(arr[i].index-start)); 
     ans=max(ans,arr[i].data*(end-arr[i].index)); 
     visited[arr[i].index]=true; 
     start=finds(visited); 
     end=finde(visited); 
     //cout<<"ans is "<<ans<<endl; 
    } 
    return ans; 
} 

错误 -

Runtime Error. Your submission stopped because of a runtime error. ex: division by zero, array index out of bounds, uncaught exception You can try testing your code with custom input and try putting debug statements in your code. 

*** Error in `./solution': munmap_chunk(): invalid pointer: 0x00000000026227c0 *** 

Aborted 
+0

100%OT - 是否有任何理由不通过const引用传递'A'?我看到你正在使用一个非const的。而不是'find' /'finde',你可以使用'std :: find'。 – Holt

+0

@请问OT是什么意思?Nd有没有使用const ref,jst习惯(我会试图改进)的特别原因。 Abt不使用find,我更喜欢使用我自己的函数,而不是内置的,因为我知道他们是如何工作的,并且帮助我创建更多符合我的需求的函数,而不是通用函数,尽管很多次它也导致了我很多问题(https:// stackoverflow.com/questions/44994718/why-does-an-inline-function-have-lower-efficiency-than-an-in-built-function?noredirect=1#comment76979854_44994718)。 – monster

+0

OT =离题(我的评论与你的问题无关)。你应该尽可能地使用标准库 - 编译器在优化自己的东西方面要比你自己的东西好得多。 – Holt

回答

1

不知道那是你的问题,但可能是一个问题

maxArea()您排序std::vectorarr

sort(arr.begin(),arr.end(),[](st a,st b)->bool{return a.data<=b.data;}); 

这是很危险的。

试着用“少”而不是“少或相等”;我的意思是

a.data < b.data; 

,而不是

a.data <= b.data; 

的问题是,std::sort()要求比较功能(称为comp())引起了严格的弱序关系。

因此它要求comp(a, a)是有史以来comp(a, b) == true暗示comp(b, a) == false

您的(原始)lambda函数不满足此要求。

+0

嗯我会从下次开始记住这一点。 nd让我试试,如果改变它解决概率 – monster

+0

改变它真的解决了我的问题。你能说出它为什么会危险吗? – monster

+3

@monster标准对'std :: sort'的'Compare'(3rd)参数有*严格的弱排序*要求,如果你不尊重,你会落入UB,所以会发生任何事情。 – Holt