【问题标题】:Efficient way to check if individual arrays inside a 2-d array have equal lengths检查二维数组中的各个数组是否具有相等长度的有效方法
【发布时间】:2017-08-26 22:45:07
【问题描述】:

假设我们有一个二维数组
int[][] arr = new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7 }, { 8, 9 } };
这里,arr[1] 的长度为3

是否有任何有效的方法来检查二维数组中存在的所有一维数组是否具有相同的长度?

说,不循环遍历数组,或者可以通过使用任何可以首选的数据结构而不是int[][]

【问题讨论】:

  • 除非您以某种有效的方式对长度进行预处理,否则您无法避免某处出现循环 - 您需要检查每个元素。
  • 谢谢,奥利弗。我正在考虑避免检查。
  • 不,我可以使用任何其他数据结构,比如 List 代替 int[][]
  • 数组从何而来?
  • 您可以在自己的类中封装一个int[][](例如IntArray2D,构造函数采用两个长度参数)以将数组限制为相同的长度。

标签: java arrays


【解决方案1】:

鉴于您在施工时间等时没有做一些簿记,您无法避免将其变成带有 nO(n) 算法> 行数。例如:

public static boolean sameLengths(int[][] matrix) {
    if(matrix == null) {
        return false;
    }
    if(matrix.length > 0) {
        if(matrix[0] == null) {
            return false;
        }
        int n = matrix[0].length;
        for(int[] row : matrix) {
            if(row == null || row.length != n) {
                return false;
            }
        }
    }
    return true;
}

边缘情况是处理null和处理没有行的矩阵。在这里我决定:

  • null 矩阵返回false
  • 行等于null 的矩阵也返回false;和
  • 一个没有行的矩阵,返回true(因为在这种情况下所有行都具有相同的长度)。

如果您以不同的方式处理这些边缘情况,则很容易更改实现。

【讨论】:

  • 谢谢,威廉。它看起来合法:)
【解决方案2】:

如果你使用 java8,下面的代码(查看内联 cmets)要简单得多,它使用基本的stream(即内部迭代)方法:

int[][] arr = new int[][] { { 1, 2 }, { 3, 4}, { 6, 7 }, { 8, 9 } }; 
final int[] firstSubArray = arr[0];//get the first array size
//Now with stream skip first element & check the size with rest
boolean isSubArraysSameSize = Arrays.stream(arr).//get stream from array
            skip(1).//skip first element
            allMatch(subArray -> 
              subArray.length == firstSubArray.length);//check rest all sizes match
System.out.println(isSubArraysSameSize);

【讨论】:

    【解决方案3】:

    在 cmets 你说我们可以使用 List。因此,请在添加新列表时检查长度差异。之后,获得答案将花费O(1):

    class DataWrapper {
        private List<List<Integer>> data = new ArrayList<>();
        private List<Integer> lastAdded;
        private boolean isDifferentLength;
    
        public void add(List<Integer> newList) {
            if (data.add(newList)) {
                if (!isDifferentLength && isDifferentLengthWith(newList)) {
                     isDifferentLength = true;
                }
                lastAdded = newList;
            }
        }
    
        private boolean isDifferentLengthWith(List<Integer> newList) {
            return lastAdded != null && lastAdded.size() != newList.size();
        }
    
        public boolean isDifferentLength() {
            return isDifferentLength;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-01
      • 2019-07-04
      • 1970-01-01
      • 2014-05-15
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      相关资源
      最近更新 更多