我几乎完成了一项家庭作业任务,乘以多项式并且必须简化它的相似术语,并且按照从最高级到最低级的顺序。 2条语句也已经排序。我的程序完美运行,但得到结果需要很长时间(比如在我的机器上运行2分钟),而我用来提交它的网站显示超出了时间限制。对于实际的乘法(这里没有显示),它需要很少的时间,但类似术语的组合需要一段时间。它发生在1个链表具有2条语句相结合,即:乘以多项式/简化类似的术语
2 2 2 1 1 1 //means 2x^2 + 2x + x
*
3 2 5 1 1 0 //means 3x^2 + 5x + 1
,我把它变成2 2 2 1 1 1 3 2 5 1 1 0进行处理。
任何人都知道我怎么能加快这一点?谢谢。
public MyLinkedList add(MyLinkedList combinedList) {
MyLinkedList tempCombinedList = new MyLinkedList();
MyLinkedList resultList = new MyLinkedList();
//check highest power now that its sorted.
tempCombinedList=null;
tempCombinedList = new MyLinkedList();
int highestPower=0;
//we need to find highest power
for(int l=2;l<=combinedList.size();l=l+2) {
if((Integer)combinedList.get(l)>highestPower) {
highestPower=(Integer)combinedList.get(l);
System.out.println("highest power is "+highestPower);
}
}
int tempAddition=0;
while(highestPower!=-1) {
for(int z=2;z<=combinedList.size();z=z+2) {
if((Integer)combinedList.get(z)==highestPower) {
tempAddition=tempAddition+(Integer)combinedList.get(z-1);
}
}
if((tempAddition!=0)) { //we arent allowed to have a 0 coefficient in there....
resultList.add(tempAddition);
resultList.add(highestPower);
}
else if(((tempAddition==0)&&(highestPower==0))) { //unless the exponent is 0 too
resultList.add(tempAddition);
resultList.add(highestPower);
}
tempAddition=0; //clear the variable for the next roud
highestPower--; //go down in power and check again.
}
return resultList;
}
你的标题说“添加”,但你的第一句话说“乘”。这是什么? – 2011-02-18 19:55:32
放入一些System.out.println(System.currentTimeMillis()),并计算出花费的时间。 – mellamokb 2011-02-18 19:57:05