PAT 甲级 1002 多项式相加(测试点2 一直不能通过)

package com.promise.pat;

import java.util.*;

public class P1002_2 {
    public static void main(String[]args){
//        使用Map
//        Key : 指数
//        value: 系数
        Scanner input = new Scanner(System.in);
        String line1 = input.nextLine();
        String line2 = input.nextLine();

        int n1 = Integer.parseInt(line1.split(" ")[0]);
        int n2 = Integer.parseInt(line2.split(" ")[0]);

        HashMap ploy1 = getData(line1,n1);
        HashMap ploy2 = getData(line2,n2);



        for (Map.Entry entry : ploy2.entrySet()) {
           Integer e =  entry.getKey();
           Double c = entry.getValue();

//           ploy1中有 ploy2的key
           if(ploy1.containsKey(e)){
               Double res = c.doubleValue() + ploy1.get(e).doubleValue();
               if(res.doubleValue() == 0){
                   ploy1.remove(e);
               }
               else{
                   ploy1.put(e,res);
               }

           }
//           ploy1中 没有 ploy2的key

           else {
               ploy1.put(e,c);
           }

        }

        int size = ploy1.size();
        if(size == 0){
            System.out.print(size);
        }
        else{
            System.out.print(size+" ");

        }

        //将keySet放入list
        ArrayList list= new ArrayList<>(ploy1.keySet());
        //调用sort方法并重写比较器进行升/降序
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 iterator = list.iterator();
        //迭代排序后的key的list
        int count = 0;
        while ((iterator.hasNext())){
            Integer key = iterator.next();
            Double value = ploy1.get(key);
            System.out.print(key.intValue()+" "+ value.doubleValue());
            count++;
            if(count != size){
                System.out.print(" ");
            }

        }




    }



    public static HashMap getData(String line, int len){
        HashMap map = new HashMap<>();

        String[] line1Date = line.split(" ");


        for(int i=1;i 
 

你可能感兴趣的:(PAT 甲级 1002 多项式相加(测试点2 一直不能通过))