锯齿状阵列;检查列值增加

时间:2016-05-24 23:00:24

标签: java arrays multidimensional-array

这个方法很简单,有2D数组,而不是矩形,目的是检查每列中的值是否增加,如果它们处于递增顺序,则返回true,否则返回false。 / p>

数组的形状如下所示,它是Young Tableaux
{
[1,4,5,10,11],
[2,6,8-],
[3,9,12],
[7]
}


年轻画面的主要特性:

  • 它由充满整数的单元组成,并排列成 左对齐的行,
  • 没有行比前一行长
  • 在任何行中从左到右,并且在整数增加的任何列中向下,
  • 使用的整数集是{1,2,... 。 。 ,n}其中n是数字 细胞


我如何解决?
我的方法很简单,首先将这个2D数组转换为矩形矩阵,如果某个位置为空,则用0填充。

然后逐个检查列,如果发现错误,则中断,然后返回结果。

它有效,我只是想知道是否有更好的装备。

public static boolean columnValuesIncrease(int[][] t) {
    //How many columns are there?
    int columnCounts = t[0].length;
    int rowCounts = t.length;

    //create a rectangle matrix, fill 0 when outIndex
    int[][] addZero = new int[rowCounts][columnCounts];
    for (int row = 0; row < rowCounts; row++) {
        for (int col = 0; col < t[0].length; col++) {
            try {
                addZero[row][col] = t[row][col];
            } catch (IndexOutOfBoundsException e) {
                addZero[row][col] = 0;
            }
        }
    }

    //Let's check the damn column!
    boolean mark = true;
    myLoop:
    for (int col = 0; col < columnCounts; col++) {
        for (int row = 0; row < rowCounts; row++) {
            if (row + 1 < rowCounts && col + 1 < columnCounts) {
                if (addZero[row + 1][col] != 0) {
                    mark = addZero[row][col] <
                            addZero[row + 1][col] ? true : false;
                }
            }
            if (!mark) {
                break myLoop;
            }
        }
    }
    return mark;
}

1 个答案:

答案 0 :(得分:2)

这种方法需要一排。它考虑了这个&#39;行和后面的那一行。它会考虑N列数,其中N是此行中的列数和后面的行数的最小值。在数学中,如果R是此2D矩阵中的行数,则取一些r 1 :r 1 ∈[0,R]和r 2 = r 1 + 1.然后,N = min { num_cols(r 1 ),num_cols(r 2 }。

nn ∈ [0, N]中,如果下一行中的列的值恰好而不是前一行中的值,则返回false 。如果其他一切都有效,则返回true。

public static boolean columnValuesIncrease(int[][] t) {
    for(int i = 0 ; i < t.length - 1 ; i++) 
        for(int j = 0 ; j < Math.min(t[i].length, t[i+1].length) ; j++) 
            if(t[i][j] > t[i+1][j])
                return false;
    return true;
}