HackerRank动态数组c#运行时错误

时间:2017-06-29 07:15:28

标签: c# data-structures

我正在尝试处理C#中动态数组的this HackerRank问题。

以下代码是我尝试过的:

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
    static void Main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
        string[] arr_temp = Console.ReadLine().Split(' ');
            long[] arr = Array.ConvertAll(arr_temp,long.Parse);
            long N = arr[0];
            long[] S = new long[]{0,0,0};
            long Q = arr[1];
            long lastAnswer = 0;
            List<long>[] list=new List<long>[100];
            for(int i=0;i<N;i++)
            {
                list[i] = new List<long>();
            }
            for(int i=0;i<Q;i++)
            {
                string[] qry_temp = Console.ReadLine().Split(' ');
                int[] qry = Array.ConvertAll(qry_temp,Int32.Parse);
                if(qry[0]==1)
                {
                    list[(qry[1] ^ lastAnswer)%N].Add(qry[2]);
                }
                else
                {                    
                    lastAnswer =  list[(qry[1] ^ lastAnswer)%N][qry[2]%(list[(qry[1] ^ lastAnswer)%N].Count)];
                    Console.WriteLine(lastAnswer);
                }

            }

    }
}

上述代码适用于小型测试用例,但对于较大值的测试用例,它显示运行时错误。 失败的测试用例: 1000 1000 1 910205855 303787404 1 710990379 16287945 。 。 。等等

如何为更大的值改进代码并使其正常工作以及数据结构的哪些属性我无法理解或丢失。

1 个答案:

答案 0 :(得分:0)

首先如果N大于a 100则会制动

List<long>[] list=new List<long>[100]//<Problem;
            for(int i=0;i<N;i++)
            {
                list[i] = new List<long>();
            }

List<long>[] list=new List<long>[N]//<Fix;
                for(int i=0;i<N;i++)
                {
                    list[i] = new List<long>();
                }

第二,因为% list[(qry[1] ^ lastAnswer) % N].Count可以为零,如果输入不正确,您将获得异常。 这个算法接近浪费时间。请注意,当您阅读Hacker这个名称时,编程90%是学习编程的一种不好的方式。