【问题标题】:Any idea why I'm getting a runtime error here?知道为什么我在这里遇到运行时错误吗?
【发布时间】:2023-04-02 16:10:01
【问题描述】:

在 HackerRank 上执行 this problem 并且我的 O(n) 解决方案通过了除最后三个之外的所有测试用例,但由于 运行时错误 而失败。不幸的是,我无法看到运行时错误是什么。当我在 Visual Studio 中运行测试时,我没有收到任何错误。知道可能导致问题的原因吗?

using System;
using System.Collections.Generic;
using System.IO;
class Solution
{
    public static void Swap(int[] A, int i1, int i2)
    {
        int temp = A[i1];
        A[i1] = A[i2];
        A[i2] = temp;
    }
    static void Main(String[] args)
    {
        int[] parameters = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
        int n = parameters[0];
        int k = parameters[1];
        int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
        int[] pos = new int[n + 1]; // pos[m] is the index of the value m in arr
        for(int i = 0; i < arr.Length; ++i)
        {
            pos[arr[i]] = i;
        }
        for(int i = 0; i < arr.Length && k > 0; ++i, --n)
        {
           if(arr[i] == n) 
               continue;
           int j = pos[n];
           Swap(pos, arr[i], n);
           Swap(arr, i, j);
           --k;
        }
        Console.WriteLine(string.Join(" ", arr));
    }
}

【问题讨论】:

  • 测试失败后,它们确实允许您使用您在网站上获得的一些积分“购买”测试用例的输入和预期输出。我知道这不是您所要求的,但这是一个可以考虑的选项。
  • 我猜int 输入无效?

标签: c# .net algorithm


【解决方案1】:

下面的部分代码是错误的,因为用户可以输入三个数字,例如 15、20、22,array.length 是 15 但你想访问索引 15、20、22... 如果您想访问这些索引,应将 pos 的长度设置为最大数量。

for(int i = 0; i < arr.Length; ++i)
{
    pos[arr[i]] = i;
}

编辑1: 如需更多指导,请说出运行时错误的代码行和消息。

【讨论】:

  • OP 链接到的问题描述指出,输入的第二行将是第一个N 整数的排列,N 是第一行提供的参数之一。如果给出了这样的输入,那么输入就与规范不符,因此程序不会被认为是明智的。