Today I studied the concept of Map in Java.
In <Thinking in Java> Map is described as : a group of key-value object pairs, allowing you to look up a value using a key. The ability to map objects to other objects can be an immensely powerful way to solve programming problems.
So the question is to add two polynomials. The format is like this:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:K N1 aN1 N2 aN2 ... NK aNK, where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1, 2, ..., K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < ... < N2 < N1 <=1000.
Sample Input
2 1 2.4 0 3.2 2 2 1.5 1 0.5Sample Output
3 2 1.5 1 2.9 0 3.2
I think to define a object of Map<Integer, Double> can solve this problem.
the code
package acm;
import java.util.HashMap;
import java.util.Scanner;
public class a1002 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
HashMap<Integer, Double> map = new HashMap<Integer, Double>();
int nNum = sc.nextInt();
for(int i = 0; i < nNum; i ++)
{
map.put(sc.nextInt(), sc.nextDouble());
}
nNum = sc.nextInt();
for(int i = 0; i < nNum; i ++)
{
int index = sc.nextInt();
double dval = sc.nextDouble();
if(map.containsKey(index))
map.put(index, dval + map.get(index));
else
map.put(index, dval);
if(map.get(index) == 0.0)
map.remove(index);
}
System.out.print(map.size() + " ");
Object[] list = map.keySet().toArray();
for(int i = list.length-1; i >= 0; i --)
{
int nKey = (Integer)list[i];
System.out.print(nKey + " ");
System.out.format("%.1f", map.get(nKey));
if(i != 0)
System.out.print(" ");
}
sc.close();
}
}
The problems I encountered were:
1. before we get an object from map, we must check if the key is in map using method of map.containKey(int );
2. It seems that it is a little complex to print the map value, especially by decrease order. Maybe I did not find a simple way.
But if we just print the values by normal order, it will be more convenient :
for(Integer key : map.keySet())
{
System.out.print(map.get(key));
}
The other problem confused me is that : java program takes more time and space to solve the same problem compared with c++.
What is more, I usually cannot pass the test case by java even some simple problem.