简体   繁体   English

为什么我在使用 ArrayList 时出现 Time Limit Exceeded (TLE) 错误<string[]>而不是 int[][]?</string[]>

[英]Why am I getting Time Limit Exceeded (TLE) error when using ArrayList<String[]> instead of int[][]?

So I was trying to implement the Floyd-Warshal algorithm for shortest distance pairs.所以我试图为最短距离对实现 Floyd-Warshal 算法。 My first implementation of the algorithm lead to time limit exceeded while the second version using a 2d array was successful.我的算法的第一个实现导致超出时间限制,而使用 2d 数组的第二个版本成功。 Can anyone point out why is the TLE coming in the first implementation?谁能指出为什么 TLE 在第一个实现中出现?
Note: 1000000 = infinity注意:1000000 = 无穷大

Input: The first line of input contains an integer T denoting the no of test cases.输入:输入的第一行包含一个 integer T 表示测试用例的数量。 Then T test cases follow.然后是 T 测试用例。 The first line of each test case contains an integer V denoting the size of the adjacency matrix.每个测试用例的第一行包含一个 integer V 表示邻接矩阵的大小。 The next V lines contain V space separated values of the matrix (graph).接下来的 V 行包含矩阵(图形)的 V 空间分隔值。 All input will be integer type.所有输入将是 integer 类型。

Output: For each test case output will be V*V space separated integers where the i-jth integer denote the shortest distance of ith vertex from jth vertex. Output:对于每个测试用例 output 将是 V*V 空格分隔的整数,其中第 i-j 个 integer 表示距第 j 个顶点的最短距离。 For INT_MAX integers output INF.对于 INT_MAX 整数 output INF。

Sample Input:样本输入:

2
2
0 25
10000000 0
3
0 1 43
1 0 6
10000000 10000000 0

Sample Output:样品 Output:

0 25 
INF 0 
0 1 7 
1 0 6 
INF INF 0 

Code approach 1 (giving TLE):代码方法1(给出TLE):

/*package whatever //do not write package name here */

import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
    public static int parseInt(String no){
        if(no.equals("10000000") || no.equals("INF")){
            return Integer.MAX_VALUE;
        }
        else
            return Integer.parseInt(no);
    }
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        StringBuffer sb = new StringBuffer();
        int t = Integer.parseInt(sc.nextLine());
        while(t-->0){
            int n = Integer.parseInt(sc.nextLine());
            ArrayList<String[]> adj = new ArrayList<>(n);
            for(int i=0;i<n;++i){
                String[] input = sc.nextLine().split(" ");
                adj.add(input);
            }
            for(int k=0;k<n;++k){
                for(int i=0;i<n;++i){
                    for(int j=0;j<n;++j){
                        int cur = parseInt(adj.get(i)[j]);
                        int iToK = parseInt(adj.get(i)[k]);
                        int kToJ = parseInt(adj.get(k)[j]);
                        int infinity = Integer.MAX_VALUE;
                        if(iToK!=infinity && kToJ!=infinity && cur>iToK+kToJ)
                            adj.get(i)[j] = Integer.toString(iToK+kToJ);
                        if(parseInt(adj.get(i)[j])==infinity)
                            adj.get(i)[j]="INF";
                    }
                }
            }
            for(int i=0;i<n;++i){
                for(int j=0;j<n;++j){
                    sb.append(adj.get(i)[j]+" ");
                }
                sb.append("\n");
            }
        }
        sc.close();
        System.out.println(sb);
    }
}

Second Approach (passed all test cases successfully):第二种方法(成功通过所有测试用例):

/*package whatever //do not write package name here */

import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        StringBuffer sb = new StringBuffer();
        int t = sc.nextInt();
        while(t-->0){
            int n = sc.nextInt();
            int[][] adj = new int[n][n];
            for(int i=0;i<n;++i)
                for(int j=0;j<n;++j)
                    adj[i][j] = sc.nextInt();
            for(int k=0;k<n;++k){
                for(int i=0;i<n;++i){
                    for(int j=0;j<n;++j){
                            adj[i][j] = Math.min(adj[i][j],adj[i][k]+adj[k][j]);
                    }
                }
            }
            for(int i=0;i<n;++i){
                for(int j=0;j<n;++j){
                    if(adj[i][j]==10000000)
                        sb.append("INF"+" ");
                    else
                        sb.append(adj[i][j]+" ");
                }
                sb.append("\n");
            }
        }
        sc.close();
        System.out.println(sb);
    }
}

In short, each iteration of the first solution is much slower than each iteration of the second one.简而言之,第一个解决方案的每次迭代都比第二个解决方案的每次迭代慢得多。 At each iteration, you do the following:在每次迭代中,您执行以下操作:

  1. Integer.parseInt , which is pretty slow. Integer.parseInt ,这很慢。 You can check this answer: https://stackoverflow.com/a/22783022/12463032 , to see that each parse takes about 60 ns, which is probably more than 10 times slower than all other operations in the loop.你可以检查这个答案: https://stackoverflow.com/a/22783022/12463032 ,看到每个解析大约需要 60 ns,这可能比循环中的所有其他操作慢 10 倍以上。 It should make sense: at the very least parseInt takes time linear on the length of the string.这应该是有道理的:至少parseInt需要时间与字符串的长度成线性关系。 Moreover, the function is not trivial (at the very least, parseInt must check that the number is an integer).此外,function 并非微不足道(至少, parseInt必须检查该数字是否为整数)。
  2. Integer.toString , which again takes time linear of the length of the string. Integer.toString ,这再次需要与字符串长度成线性关系的时间。 Moreover, it involves object (string) creation, and your time may increase because of memory processing (eg GC may not work that well in your settings, and don't forget about memory allocation).此外,它涉及 object(字符串)的创建,并且您的时间可能会因为 memory 处理而增加(例如 GC 在您的设置中可能无法正常工作,并且不要忘记 ZCD69B4957F06CD818D7ZBF3D61980E291 分配)。

On a higher level, you violate Item 50 from "Effective Java" ( http://wavelino.coffeecup.com/pdf/EffectiveJava.pdf ): Avoid strings when other types are more appropriate .在更高的层面上,您违反了“有效 Java”中的第 50 条( http://wavelino.coffeecup.com/pdf/EffectiveJava.pdf ):当其他类型更合适时避免使用字符串 You perform numerical computations on your data;您对数据进行数值计算; therefore, you should store them as numbers.因此,您应该将它们存储为数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我超出了时间限制? - Why am i getting time limit exceeded? 为什么我在 Java 中超过了时间限制? - Why I am getting Time Limit Exceeded in Java? 如何删除此 java 代码的 Time Limit Exceeded(TLE) 错误 - How to remove Time Limit Exceeded(TLE) error for this java code 如何将我的第一个程序提交到SPOJ平台? 为什么我超出时间限制或运行时错误NZEC? - How to submit my first program to SPOJ platform? Why I am getting time limit exceeded or runtime error NZEC? 当我尝试运行此代码时,出现时间限制超出错误,执行需要 1.01 毫秒 - When I try to run this code I am getting time limit exceeded error and it's taking 1.01 ms to execute 谁能解释我如何克服 Java 中的 TLE 错误。 我在 3 个输入中超过了 Time Limit Exceeded,这些输入将 100000 个测试用例作为输入 - Can anyone explain me how to overcome TLE error in Java. I'm getting Time Limit Exceeded in 3 inputs which are taking 100000 test cases as input 阵列旋转 TLE(超出时间限制) - Array rotation TLE (Time Limit Exceeded) 超出圆形阵列旋转时间限制(TLE) - Circular Array Rotation Time Limit Exceeded(TLE) 我不确定为什么要获得Codechef的TLE - I am not sure why I am getting a TLE for codechef 将对象添加到ArrayList时为什么出现此错误-Java - Why am I getting this error when adding object to ArrayList - Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM