java自习室 day 10

题目

给定一维整型数组array,求将其变为n*n的二维数组再按列输出后得到的一维数组。
例:输入:array=[1,2,3,4,5,6,7,8,9],n=3
1 2 3
4 5 6
7 8 9
输出 1 4 7 2 5 8 3 6 9
当array长度比n^2大或者小时应该怎么处理?
算出前后两个数组的下标转化表达式,直接计算得出结果:
新数组newArray下标设为i,对应的旧数组array下标为index,遍历一次newArray,每遍历n个数,loop++。
i n d e x = ( i % n ) ∗ n + l o o p index = (i\%n)*n+loop index=(i%n)n+loop

    public Integer[] crossCoding1(Integer[] array,int n){
        if(array==null){
            return null;
        }
        int length = array.length;
        if(array.length == 0){
            return array;
        }
        int n1 = n*n;int cols = n;int n2,newLen;
        if(length>n1){
            //array转化成的二维数组的行数
            cols = length/n==0?length/n:length/n+1;
            int temp = n;
            while((temp++)*temp<length){}
            //array转化成的二维数组的大小
            n2 = temp*temp;
            newLen = n2;
        }
        else{
            newLen = n1;
        }
        Integer[] copy = new Integer[newLen];
        //补齐array,不够的补null
        for (int i = 0; i < newLen; i++) {
                if(i<length) {
                    copy[i] = array[i];
                }
                else{
                    copy[i] = null;
                }
            }
        Integer[] newArray = new Integer[newLen];
        Integer[] result = new Integer[length];
        int loop = 0;int index;int newIndex=0;
        for (int i = 0; i < newLen; i++) {
            index = n * (i % cols) + loop;
            if(copy[index] != null) {
                newArray[newIndex++] = copy[index];
            }
            if(i%cols == cols-1){
                loop++;
            }
        }
        //null全部集中在最后面,直接抛弃
        for (int i = 0; i < length; i++) {
            result[i] = newArray[i];
        }
        return result;
    }
 }

测试用例:

public static void main(String[] args) {
        CrossCoding cc = new CrossCoding();
        Integer[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
        int n=3;
        Integer[] newArray;
        newArray = cc.crossCoding1(array,n);
        for (int i = 0; i < newArray.length; i++) {
            System.out.print(newArray[i]+" ");
        }
    

输出:1 4 7 10 13 16 2 5 8 11 14 3 6 9 12 15

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值