publicclassMatrix{booleanisReshapable(intlength,introw,intcol){if(length<0||row<0||col<0){returnfalse;}if(length==0){if(row==0&&col==0){returntrue;}else{returnfalse;}}if(...
public class Matrix {
boolean isReshapable(int length, int row, int col) {
if (length < 0 || row < 0 || col < 0) {
return false;
}
if (length == 0) {
if (row == 0 && col == 0) {
return true;
} else {
return false ;
}
}
if (length == row * col) {
return true;
}
return false;
}
将下列方法加到上述Matrix的class中去, int[][] reshape(int[] vector, int row, int col) : 重新塑造这个补充的变量成一个2维阵列或者是一个矩阵或者是一个特定的大小。输出一个新的Matrix。如果这个变量是不可重新塑造的话, 输出null。
import java.util.Arrays;
...
Matrix m = new Matrix();
int[] vector = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
System.out.println(Arrays.deepToString(m.reshape(vector, 2, 6))); //prints "[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]"
System.out.println(Arrays.deepToString(m.reshape(vector, 3, 4))); //prints "[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]"
展开