2021 阿里笔试题 完美对

完美对

题目链接
其实规律在于ai-aj=-(bi-bj)
那么只需要一个map来存储这个序列的差并作为自己的code,用两个map统计优化,就能实现快速的查询

import java.util.*;
public class Main {

    //设计获取反向code
    public static String getAnti(String code){
        StringBuilder s = new StringBuilder();
        for(int i = 0;i<code.length();i++){
            char c = code.charAt(i);
            if(c == '+')
                s.append('-');
            else if(c=='-')
                s.append('+');
            else
                s.append(c);
        }
        return s.toString();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n, k;
        n = scanner.nextInt();
        k = scanner.nextInt();
        int[][] array = new int[n][k];
        for(int i = 0; i<n;i++){
            for(int j = 0;j<k;j++){
                array[i][j] = scanner.nextInt();
            }
        }
        //负责统计相同的code有多少
        Map<String,Integer> map = new HashMap<>();
        //负责存自己的code
        Map<Integer,String> imap = new HashMap<>();
        int allSame = 0;
        for (int i = 0; i < n; i++) {
            int zeros = 0;
            StringBuilder code = new StringBuilder();
            for (int j = 0; j < k; j++) {
                if(j!=0){
                    int a = array[i][j] - array[i][j-1];
                    if(a > 0){
                        code.append('+').append(a);
                    }
                    else if(a==0){
                        //特判0的情况 后面就不需要处理符号0了
                        code.append('.').append(a);
                        zeros ++;
                    }else{
                        code.append('-').append(Math.abs(a));
                    }
                }
            }
            if(zeros == k-1)allSame++;//差值都是0才会匹配自己
            imap.put(i,code.toString());
            if(map.containsKey(code.toString())){
                map.put(code.toString(),map.get(code.toString())+1);
            }else{
                map.put(code.toString(),1);
            }
        }
        //统计匹配数
        int res = 0;
        for(int i = 0; i < n ;i++){
            String code = imap.get(i);
            String antiCode = getAnti(code);
            if(map.containsKey(antiCode))
                res += map.get(antiCode);
        }
        //最后得到的是总匹配数 要减掉每一项都是0的元素 再除以2
        res -= allSame;//去掉匹配自己本身的
        res /= 2;//匹配数除以2
        System.out.println(res);
    }
}

一次过,非常快乐
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值