牛客编程入门—序列重组矩阵

在这里插入图片描述

解法思路:
直接用两个for循环实现在接收数组元素的同时将元素输出。

import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int m = scan.nextInt();
        int[][] a = new int[n][m];
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                a[i][j] = scan.nextInt(); //输入元素
                System.out.print(a[i][j]+ " "); //输出元素
            }
            System.out.println(); //换行
        }
    }
}

优化后的代码,这个优化在解题思路上并没有什么创新,只是代码运行时间和内存得到一定的优化。只是要注意这种解法引入了count作为一个累加器。

import java.io.*;

public class Main{
    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] str = br.readLine().split(" ");
        int n = Integer.parseInt(str[0]);
        int m = Integer.parseInt(str[1]);
        str = br.readLine().split(" ");
        int[][] a = new int[n][m];
        int count = 0;
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                a[i][j] = Integer.parseInt(str[count]);
                System.out.print(a[i][j]+ " ");
                count++;
            }
            System.out.println();
        }
    }
}

另一种解题思路
利用str = br.readLine().split(" ");获取数组中的元素,然后用一个上界为数组长度的for循环来输出元素,如果遇到输出元素的列数等于矩阵的列数,则输出元素后换行,这样便能输出一个矩阵。

import java.io.*;

public class Main{
    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] str = br.readLine().split(" ");
        int n = Integer.parseInt(str[0]); //矩阵行数
        int m = Integer.parseInt(str[1]); //矩阵列数
        str = br.readLine().split(" "); //获取数组中的元素
        for(int i = 0; i < str.length; i++){
            if((i + 1) % m == 0){ //如果列数与m相等,则输出元素并换行
                System.out.println(str[i] + " ");
            }else {
                System.out.print(str[i] + " ");
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值