如何减少记忆:

时间:2016-12-01 22:26:23

标签: java memory

我需要创建输入图(带有向后边的图)。例如:1-st图的边缘从1到2,从2到3;输入图的边长为3到2,从2到1。 问题是我正在创建矩阵(N ^ N内存使用)。如何使用更少的内存来完成这项任务?

import java.util.Scanner;

public class ReverseGraph{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int n = Integer.parseInt(scan.nextLine()); // number of vertices
        //matrix of vertices
        int[][] matrix = new int[n][n];
        Scanner sc;
//create graph by input method(if A vertex associates with B vert than put "1" on B row, A column)
        for(int i = 0; i < n;i++){
            String line = scan.nextLine();
            sc = new Scanner(line);
            while(sc.hasNextInt()){
                matrix[sc.nextInt() - 1][i] = 1;
            }

        }
        scan.close();

//Begin write the input graph       
        System.out.println(n); //write num of vertices

        //write
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                if(matrix[i][j] == 1)
                    System.out.print((j+1) + " ");
            }
            System.out.println();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

减少内存占用的选项。

  • 作为ArrayList<int[]>实现的邻接列表,其中int[]是2个元素的数组,每个数组代表一个链接。

  • 如上所述,除了使用带有两个int字段的自定义类来表示链接。

  • 作为HashMap<Integer, HashSet<Integer>>HashMap<Integer, HashSet<Integer>>HashMap<Integer, TreeSet<Integer>>,其中每个集或列表代表链接的目的地。

  • 使用Trove collection types等效于上述内容。

所有这些 1 对于链接数量O(L)而不是数量O(N^2)的节点。

1 - 除了使用TreeSet ...

的变体
相关问题