`

取二维数组的所有列的最小值组成一个数组

 
阅读更多

package demo;

import java.util.Arrays;

/**
 * 取二维数组的所有列的最小值组成一个数组
 */
public class Ary {
 public static void main(String[] args) {
  int[][] iAry = {{1, 5, 2},{3, 4, 6, 2}};
  int rows = iAry.length;
  System.out.println("二维数组为:");
  /**
    当然下面可以使用
   System.out.println(Arrays.deepToString(iAry));
   来打印该二维数组,但打印出来后不利于查看
   */
  for(int row = 0; row < rows; row++){
   for(int col = 0; col < iAry[row].length; col++){
    System.out.print(iAry[row][col] + "\t");
   }
   System.out.println();
  }
  int colMax = iAry[0].length;
  for(int row = 1; row < rows; row++){
   if(iAry[row].length > colMax){
    colMax = iAry[row].length;
   }
  }
  System.out.println("该二维数组的最大列数为:" + colMax);
  int[] ary = new int[colMax];
  //将小于最大列的行补充0至最大列数
  for(int row = 0; row < rows; row++){
   if(iAry[row].length < colMax){
    iAry[row] = Arrays.copyOf(iAry[row], colMax);
   }
  }
  for(int col = 0; col < colMax; col++){
   int min = iAry[0][col];
   for(int row = 1; row < rows; row++){
    if(iAry[row][col] < min){
     min = iAry[row][col];
    }
   }
   System.out.println("第" + col + "列的最小值为:" + min);
   ary[col] = min;
  }
  System.out.println("取该二维数组的所有列的最小值组成的一维数组为:" + Arrays.toString(ary));
 }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics