【发布时间】:2015-12-02 09:40:07
【问题描述】:
我想写一个多项式的导数方法。我的输入格式是存储度数和系数的 HashMap。如果多项式有很多零系数,这种方式(与数组类型输入相比)在空间方面更好,但根据我的代码,我需要迭代 n 次,其中 n 是多项式的次数,而不是 HashSet 的大小。就像 1+x^100 的 HashMap 大小为 2,但度数为 100。为了降低时间复杂度,我只需要对 HashSet 进行计算。我们可以将迭代次数从 n 减少到 HashMap 大小吗?这是我的代码:
public static HashMap<Integer, Double> derivativePoly2(HashMap<Integer, Double> degreeAndCoeff) {
int len = degreeAndCoeff.size();
int i = 0;
while (i < Integer.MAX_VALUE && len - 1 > 0) {
if (degreeAndCoeff.containsKey(i + 1)) {
--len;
degreeAndCoeff.put(i, degreeAndCoeff.get(i + 1) * (i + 1));
degreeAndCoeff.remove(i + 1);
}
++i;
}
return degreeAndCoeff;
}
【问题讨论】:
标签: java performance time iterator hashmap