2017-04-01 44 views
1

假设我们有一个2D阵列
int[][] arr = new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7 }, { 8, 9 } };
这里,arr[1]具有3的长度。高效的方式,如果有2 d阵列内单独的阵列具有相等的长度

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

说,没有通过数组循环或可能通过使用任何数据结构可以是首选而不是int[][]

+0

除非你以某种有效的方式预处理的长度,你不能避免环路的地方 - 你需要检查每一个元素。 –

+0

谢谢,奥利弗。我正在考虑避免检查。 –

+0

不,我可以使用任何其他数据结构,比如列表代替int [] [] –

回答

1

鉴于你不施工时间做一些簿记等你无法避免把这个变成一个O(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什么用矩阵没有行。这里我决定:

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

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

+0

谢谢,威廉。它看起来合法:) –

2

如果使用java8,下面的代码(看在线评论)要简单得多,它使用基本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); 
1

在你说我们可以使用注释a 列表。因此,请在添加新列表时检查长度差异。在此之后,得到的答案将耗资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; 
    } 
}