【问题标题】:Maximum sum of lengths of non-overlapping contiguous subarrays非重叠连续子数组的最大长度总和
【发布时间】:2018-01-19 16:59:32
【问题描述】:

我正在尝试实施amazon 面试问题。

Find the maximum sum of lengths of non-overlapping contiguous subarrays with k as the maximum element.
Ex: Array: {2,1,4,9,2,3,8,3,4} and k = 4
Ans: 5
{2,1,4} => Length = 3
{3,4} => Length = 2
So, 3 + 2 = 5 is the answer

我有实现程序:

#include <iostream>
using namespace std;

int main()
{
        int a[] = {2,1,4,9,2,3,8,3,4,2};
        int cnt = 0, i = 0, j = 0, ele, k = 4;
        int tmp = 0, flag = 0;

        ele = sizeof(a)/sizeof(a[0]);

        for(j = 0; j < ele; )
        {
                i = j;
              //while( i < ele && a[i++] <= k) //It's working fine
                while(a[i] <= k && i++ < ele)  // It's not work
                {
                        cnt++;
                        cout<<"while"<<endl;
                }

                while(j < i)
                {
                        if(a[j++] == k)
                        {
                                flag = 1;
                        }
                }

                if(flag == 1)
                {
                        tmp += cnt;
                        flag = 0;
                }
                cnt = 0;
                j = i;
        }
        cout<<"count : "<<tmp<<endl;
        return 0;
}

在我的程序中,我使用了

while( i < ele && a[i++] <= k)

它工作正常并提供正确的输出。

但是,如果我使用

while(a[i] <= k && i++ < ele)

然后我的程序卡住了。为什么?

【问题讨论】:

  • [OT]:你可以像that这样简化你的代码

标签: c++ arrays post-increment


【解决方案1】:

使用while(a[i] &lt;= k &amp;&amp; i++ &lt; ele),您实际上可以超出数组a 的范围,导致undefined behavior

如果i是数组的最后一个索引,那么i++ &lt; ele实际上就是true(因为后缀++操作符在递增之前返回了old值),然后在循环i 将超出范围。

未定义的行为,嗯,未定义,可能意味着几乎任何事情都可能发生。从崩溃到无限或卡住的循环。

更好的解决方案是使用 prefix 增量,如++i &lt; ele

【讨论】:

  • isnt 已经是UB,因为i++a[i] 出现在同一个表达式中?
  • @tobi303 不,左侧在&amp;&amp;|| 表达式的右侧之前排序(参见例如this evaluation order reference,尤其是rule 6)。
【解决方案2】:

while( i &lt; ele &amp;&amp; a[i++] &lt;= k)while(a[i] &lt;= k &amp;&amp; i++ &lt; ele) 的区别在于: while( i &lt; ele &amp;&amp; a[i++] &lt;= k) 将首先增加 i 并稍后获取值,但 while(a[i] &lt;= k &amp;&amp; i++ &lt; ele) 将首先比较 iele 然后增加 i

所以在你的代码中,当程序用完 while(a[i] &lt;= k &amp;&amp; i++ &lt; ele) 时,i 等于 3,但 while( i &lt; ele &amp;&amp; a[i++] &lt;= k) 等于 4。这就是问题造成的原因

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 2019-12-25
    • 2011-05-28
    • 1970-01-01
    • 2021-01-15
    • 2015-07-27
    相关资源
    最近更新 更多