C ++ HackerRank-数组操作

时间:2018-09-10 20:57:22

标签: c++ arrays segmentation-fault

这是我要解决的问题,在上一节中,我尝试将所有问题汇总在一起。

我能够通过11个测试用例,但是提交人抱怨使用非常大的n和m的测试用例存在分段错误。 https://www.hackerrank.com/challenges/crush/problem

简而言之,问题是希望基于查询向量中的元素在init_array中添加元素。

这是我解决问题的代码。注意:我将数据类型“ int”更改为“ long unsigned int”,因为某些输出结果为32767。

// Complete the arrayManipulation function below.
unsigned long int arrayManipulation(unsigned long int n,
                                    vector<vector<unsigned long int>> queries) {
    unsigned long int init_array[n+1]={0};
    unsigned long int max = init_array[0];
    for(unsigned long int i=0; i<queries.size();++i)//m
    {
      for(unsigned long int j=queries.at(i).at(0); j<=queries.at(i).at(1); ++j)
      {

         init_array[j-1]+=queries.at(i).at(2);

          if(init_array[j-1] > max)
              max = init_array[j-1];
      }
    }

    return max;
}

我的代码失败的测试用例之一:

输入:

10000000 100000

1449932 7787270 51019
912262 3955862 23367
720355 6300425 44414
4058050 4109759 82390
630827 1992079 83163
4595878 6289869 37323
6117634 7440834 53818
3577465 5755968 89549
611287 4779893 49153
6118450 8290500 9271
6328120 8594121 59202
695492 2549982 71464
1366758 8035211 8170
5476516 5979625 82571
2378367 9984946 13398
4580824 5961530 19618
3214809 9215205 60451
1487128 5985376 37916
574925 6267020 65554
2340430 4901822 56053
749701 1229941 50173
1925432 3125256 16506
2476995 6413072 83263
972971 2937594 59778
3351338 3520166 61075
1829219 7249916 41898
1044424 7269534 73058
4729986 9546151 60185
121075 8284254 27205
2449808 2461505 29026
5727557 7422213 75318
988738 1369164 17102
7105244 7782235 94096
719829 7104859 67066
2580989 6756346 18403
4006261 8042064 47622
600315 3792146 8397
1038483 6373373 54547
3633559 9322736 91973
4288895 7160764 69829
1711107 8106142 97386
281460 5216196 66549
2321439 6898562 65136
5992658 9426297 1316
2007285 8576077 57661
2565701 4510

<<请使用下载链接查看完整的输入测试用例>>

预期输出:

2484930878
  1. 此代码适用于较小的n和m,分别约为4000和30000。为什么我看到n或m大的分割错误问题?

  2. 以上算法的复杂性是什么?平均O(m log n)?对于每个“ m”次迭代,我仅对“ n”个索引的子集运行第二个循环。

1 个答案:

答案 0 :(得分:2)

我怀疑您的init_array溢出了堆栈。尝试改用vector

vector<unsigned long int> init_array(n);