标签:02 HashMap int 多项式 PTA map2 map1 key 数据结构
一、题目
设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式:
输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0
。
输入样例:
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
输出样例:
15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0
二、解答
import java.util.*;
public class Main {
public static void main(String[] args) {
//指数为key,系数为value,存放成map
HashMap<Integer,Integer> map1 = new HashMap<>();
HashMap<Integer,Integer> map2 = new HashMap<>();
Scanner sc = new Scanner(System.in);
int len1 = sc.nextInt();
for (int i = 0; i < len1 ; i++) {
int value = sc.nextInt();
int key = sc.nextInt();
map1.put(key, value);
}
int len2 = sc.nextInt();
for (int i = 0; i < len2 ; i++) {
int value = sc.nextInt();
int key = sc.nextInt();
map2.put(key, value);
}
printMap(multiply(map1,map2));
printMap(add(map1,map2));
}
public static HashMap<Integer,Integer> multiply(HashMap<Integer,Integer>map1, HashMap<Integer,Integer>map2){
HashMap<Integer,Integer> res = new HashMap<>();
for (int key1 : map1.keySet()) {
for (int key2 : map2.keySet()){
int newKey = key1+key2;
int newValue = map1.get(key1) * map2.get(key2);
if (res.containsKey(newKey)){
newValue = res.get(key1+key2) + newValue;
res.put(newKey,newValue);
} else {
res.put(newKey,newValue);
}
}
}
return res;
}
public static HashMap<Integer,Integer> add(HashMap<Integer,Integer>map1, HashMap<Integer,Integer>map2){
for (int key : map2.keySet()){
if (map1.containsKey(key)){
int newValue = map1.get(key) + map2.get(key) ;
map1.put(key,newValue);
} else {
map1.put(key,map2.get(key));
}
}
return map1;
}
public static void printMap(HashMap<Integer,Integer> map){
ArrayList<Integer> keys = new ArrayList<>(map.keySet());
Collections.sort(keys, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (o1>o2) return -1;
else if (o1<o2) return 1;
else return 0;
}
});
String res = "";
for (int key : keys) {
if (map.get(key)!=0) res = res + map.get(key) + " " + key + " ";
}
if (res.equals("")) res = "0 0";
System.out.println(res.trim());
}
}
- 解题思路:指数为key,系数为value,存放成map
- List可以直接用Collections的sort()方法进行排序,默认从小到大,此题重写了排序方式为从大到小
- 看清题干:全零多项式输出为0 0
- 如果只是一元多项式相加,可以考虑使用链表做
标签:02,HashMap,int,多项式,PTA,map2,map1,key,数据结构 来源: https://blog.csdn.net/hdu_ch/article/details/102726418
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。