【校招笔试】二维数组打印(模拟,规律)

时间限制:3秒 空间限制:32768K
热度指数:1160
本题知识点: 数组
题目描述

有一个二维数组(n*n),写程序实现从右上角到左下角沿主对角线方向打印。
给定一个二位数组arr及题目中的参数n,请返回结果数组。

测试样例

[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]],4

返回

[4,3,8,2,7,12,1,6,11,16,5,10,15,9,14,13]


代码:

import java.util.*;

//比较器
class Comparators {
    public static Comparator getComparator() {
        return new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Integer) {
                    return compare( (Integer) o1, (Integer) o2);
                } else return 1;
            }

            public int compare(Integer s1, Integer s2) {
                return s2-s1;
            }

        };
    }
}

public class Main {

    public static int[] arrayPrint(int[][] arr, int n) {
        // write code here
        int[] ans = new int[n*n];
        int x = 0, y = n-1;
        int num = 0;
        int flag = 0;
        for(int i = 0; i < 2*n-1; i++) {
            int xx = x, yy = y;
            while(xx!=n && yy!=n) {
                ans[num++] = arr[xx][yy];
                xx++;
                yy++;
            }
            if(x == 0 && y == 0){
                x = 1;
                flag = 1;
            }
            else{
                if(flag == 0) {
                    x = (x != 0 ? x-1 : 0);
                    y = (y != 0 ? y-1 : 0);
                } else {
                    x = (x != 0 ? x+1 : 0);
                    y = (y != 0 ? y+1 : 0);
                }

            }
        }
        return ans;
    }

    /*
        测试代码
     */
    public static void main(String []args){
        /*Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){

        }*/
        int[][] arr = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}};
        int n = 4;
        int[] ans = arrayPrint(arr, n);
        for(int i = 0; i < n*n; i++) {
            System.out.print(ans[i]+" ");
        }
        System.out.println();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值