判断两个数组内容是否相等(繁琐)

判断两个数组内容是否相等

通过这个案列巩固相关知识点

package com.company;

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] list1 = {
                {51,25,22},
                {6,1,4},
                {24,54,6}
        };

        int[][] list2 = {
                {51,22,25},
                {6,1,4},
                {24,54,6}
        };

        System.out.printf("The two arrays are %s\n",equals(list1,list2) ? "identical" : "not identical");
    }

    //假设m1,m2均为n*n的二维数组
    public static boolean equals(int[][] m1, int[][] m2){
        return equals(distinctArray(m1), distinctArray(m2));
    }

    //判断两个一维数组是不是严格相等
    public static boolean equals(int[] list1, int[] list2){
        boolean out = true;
        if(list1.length != list2.length){
            out = false;
        }else{
            for(int i = 0; i < list1.length; i++){
                out = out && list1[i] == list2[i];
                if(!out)
                    break;
            }
        }

        return out;
    }

    //将二维数组逐个去除元素,排除重复后,放入一维数组 (尾部去掉元素为0), 后排序再返回
    public static int[] distinctArray(int[][] m){
        int distinctNumbers = 0;
        int[] result = new int[m.length * m[0].length];
        for(int row = 0; row < m.length; row++){
            for(int column = 0; column < m[row].length; column++){
                if(!isInArray(result,m[row][column])){
                    result[distinctNumbers++] = m[row][column];
                }
            }
        }

        int[] result1 = new int[distinctNumbers];
        for(int i = 0; i < result1.length; i++){
            result1[i] = result[i];
        }
        Arrays.parallelSort(result1);

        return result1;
    }

    //判断一个值是否在一维数组中
    public static boolean isInArray(int[] list,int key){
        boolean out = false;
        for(int i = 0; i < list.length; i++){
            if(key == list[i]){
                out = true;
                break;
            }
        }

        return out;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值