【问题标题】:Geeksforgeeks is showing my code as runtime error after submissionGeeksforgeeks 在提交后将我的代码显示为运行时错误
【发布时间】:2018-08-02 05:08:58
【问题描述】:

这是我的代码

#include <bits/stdc++.h>
using namespace std;

int srch(vector<int> arr, int ln, int fn)
{
    for (int i = 1; i <= ln; i++)
{
    if (arr[i] == fn)
        return i;
}
return -1;
}

int main()
{
int t;
scanf("%d", &t);
while (t--)
{
    int n, k;
    scanf("%d%d", &n, &k);
    vector<int> a(n);
    for (int i = 1; i <= n; i++)
        scanf("%d", &a[i]);
    printf("%d\n", srch(a, n, k));
}
return 0;
}

我不明白问题出在哪里。这是问题链接Click here。 请帮我解决这个问题。我不明白为什么 geeksforgeeks 显示此代码的运行时错误。

【问题讨论】:

    标签: algorithm sorting linear-search


    【解决方案1】:

    请注意,您的循环使用向量的第 n 个条目,但是

    vector< int> a(n);
    

    索引从 0 到 n-1

    Notice that the first element has a position of 0 (not 1).

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-09
      • 1970-01-01
      • 2018-12-09
      • 2012-04-20
      • 1970-01-01
      • 2022-01-23
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多