1 题目要求:
https://www.patest.cn/contests/pat-a-practise/1002
2 源代码
import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.Scanner; import java.util.Stack; import java.util.TreeMap; public class Main { public static void main(String[] args) { Scanner input= new Scanner(System.in); String[] line1 = input.nextLine().trim().split(" "); String[] line2 = input.nextLine().trim().split(" "); int k1 =Integer.parseInt(line1[0]); int k2 =Integer.parseInt(line2[0]); TreeMap<Integer,Double > map = new TreeMap<Integer,Double>(); for(int i=1;i<2*k1+1;i=i+2) { int key = Integer.valueOf(line1[i]); double value = Double.valueOf(line1[i+1]); map.put(key, value); } for(int i=1;i<2*k2+1;i+=2) { int key = Integer.valueOf(line2[i]); double value = Double.valueOf(line2[i+1]); if(map.containsKey(key)) { value=value+map.get(key); if(value==0) { map.remove(key); }else { value=Math.round(value*10)/10.0; map.put(key,value); } }else { value=Math.round(value*10)/10.0; map.put(key,value); } } Iterator<Integer> it=map.keySet().iterator(); Stack<Integer> stack = new Stack<Integer>(); while(it.hasNext()) { stack.push(it.next()); } System.out.print(map.size()); while(!stack.isEmpty()) { System.out.print(" "+stack.peek()); System.out.print(" "+map.get(stack.pop())); } } }
3 评测结果
4 这题的难度很大,用了很多自己不熟悉的知识点,map集合,栈,迭代器,key value以及数据类型Integer的intValue方法,valueOf方法,能把这个代码写出来,说明java基础很扎实,对数据结构的了解也很厉害。再次提醒:提交的时候一定要注意先在编译器上编译通过,然后去掉包名,以及Main改好,不要少东西,也不要多东西。
package bowen1233; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.Scanner; import java.util.Stack; import java.util.TreeMap; public class Main1 { public static void main(String[] args) { Scanner input= new Scanner(System.in); //用这种形式接收数据,比用for循环接收数据快的多,并且数据类型方便一点吧,用for循环读入数据也可以。double型数组,但是输出后面会带10.0 String[] line1 = input.nextLine().trim().split(" "); String[] line2 = input.nextLine().trim().split(" "); int k1 =Integer.parseInt(line1[0]); int k2 =Integer.parseInt(line2[0]); TreeMap<Integer,Double > map = new TreeMap<Integer,Double>(); //将第一个多项试的值加到map集合中 for(int i=1;i<2*k1+1;i=i+2) { int key = Integer.valueOf(line1[i]); double value = Double.valueOf(line1[i+1]); map.put(key, value); } for(int i=1;i<2*k2+1;i+=2) { int key = Integer.valueOf(line2[i]); double value = Double.valueOf(line2[i+1]); if(map.containsKey(key)) { value=value+map.get(key); if(value==0) { map.remove(key); }else { value=Math.round(value*10)/10.0; map.put(key,value); } }else { value=Math.round(value*10)/10.0; map.put(key,value); } } //定义迭代器,迭代key值 Iterator<Integer> it=map.keySet().iterator(); //定义栈,将key值放入栈中 Stack<Integer> stack = new Stack<Integer>(); //迭代,获取key值,放入栈中 while(it.hasNext()) { stack.push(it.next()); } System.out.print(map.size()); while(!stack.isEmpty()) { System.out.print(" "+stack.peek()); System.out.print(" "+map.get(stack.pop())); } } }