【问题标题】:get 2d arraylist elements - java获取二维数组列表元素 - java
【发布时间】:2016-09-25 22:10:42
【问题描述】:

我正在尝试为 2D ArrayList 实现螺旋输出。我在第 38 行收到 IndexOutOfBoundsException 错误: result.add(a.get(rightColumn).get(i));

我的代码在逻辑上对我来说是正确的。我不确定我在哪里犯了错误。有人可以给我一个关于如何解决这个问题的线索吗?谢谢!

import java.util.*;

public class Solution {
public static ArrayList<Integer> spiralOrder(final List<ArrayList<Integer>> a) {
     ArrayList<Integer> result = new ArrayList<Integer>();

     int direction = 0;

     /*
     *  0 for left to right
     *  1 for top to bottom
     *  2 for right to left
     *  3 for bottom to top
     */

     int topRow = 0;
     int bottomRow = a.size() - 1;

     int leftColumn = 0;
     int rightColumn = a.get(0).size() - 1;


     while (topRow <= bottomRow && leftColumn <= rightColumn) {

         if (direction == 0) {
           for (int i = leftColumn; i <= rightColumn; i++) {
               result.add(a.get(topRow).get(i));

           }  

           topRow++;
           direction = 1;
         }

         else if (direction == 1) {
             for (int i = topRow; i <= bottomRow; i++) {
                 result.add(a.get(rightColumn).get(i));

             }

             rightColumn--;
             direction = 2;
         }

         else if (direction == 2) {
             for (int i = rightColumn; i>= leftColumn; i--) {
                 result.add(a.get(bottomRow).get(i));

             }

             bottomRow--;
             direction = 3;
         }

         else if (direction == 3) {
             for (int i = bottomRow; i >= topRow; i--) {
                 result.add(a.get(leftColumn).get(i));

             }

             leftColumn++;
             direction = 0;
         }


     }


     for (int i = 0; i < result.size(); i++) {
         System.out.println(result.get(i));
     }

     return result;
}

public static void main (String[] args) {
    List<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();

    ArrayList<Integer> row1 = new ArrayList<Integer>();
    ArrayList<Integer> row2 = new ArrayList<Integer>();
    ArrayList<Integer> row3 = new ArrayList<Integer>();

    row1.add(1);
    row1.add(2);
    row2.add(3);
    row2.add(4);
    row3.add(5);
    row3.add(6);



    list.add(row1);
    list.add(row2);
    list.add(row3);

    spiralOrder(list);

}
}

【问题讨论】:

    标签: java arraylist multidimensional-array 2d


    【解决方案1】:

    也许你应该在 for 之外增加 toprow

    for (int i = leftColumn; i <= rightColumn; i++) {
           result.add(a.get(topRow).get(i));
    
       }
     topRow++;
    

    【讨论】:

    • 和 if too
    • 嘿,谢谢你的帮助。我现在已经更新了这个问题。现在我在第 37 行收到此错误
    • 你应该只用顶部和底部索引 a.ger。花点时间想想你在做什么。建议:您应该考虑使用两个 while 循环而不是一个。
    • 啊,犯了一个愚蠢的错误。应该是 result.add(a.get(i).get(rightColumn));我错误地交换了列和行。
    猜你喜欢
    • 2019-03-23
    • 1970-01-01
    • 2021-12-31
    • 2020-05-03
    • 2015-11-29
    • 2011-01-03
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多