[英]How to sum two double linked lists in one list efficiently?
例如 listA = [3,6,7,4] 和 listB = [2,3,1] 并且 output 必须是 listC=[5,9,8,6]。 到目前为止,这是我所拥有的,但效率不高。
`public void sum(doublelist aList) {`
for (int i = 0; i < size(); i++) {
set(i, this.get(i) + other.get(i % other.size()));
}
}
正如您所说,您正在使用链表,您可以从一个元素导航到另一个元素:
public void sum(DoubleList aList){
DoubleNode cur=this.head;
DoubleNode other=aList.head;
while(cur!=null){
cur.setValue(cur.getValue()+other.getValue());
other=other.getNext();
if(other==null){
other=aList.head;
}
cur=cur.getNext();
}
}
此代码假定您的DoubleList
包含类型为DoubleNode
的名为head
的头节点属性,并且DoubleNode
具有用于访问值的方法double getValue()
/ void setValue(double value)
和用于检索下一个元素的DoubleNode getNext()
方法。
这应该更有效,因为您不必每次都查询列表( O(n)
而不是O(n^2)
)。
答案完全取决于您使用的是哪种列表。
但无论如何,您可以获得的最佳复杂度是 O(n),您将必须对列表的每个元素至少迭代一次。
最简单的是使用 ListIterator,它允许在遍历列表时设置一个值。
void sum(List<Integer> l1, List<Integer> l2) {
final ListIterator<Integer> it1 = l1.listIterator();
final Iterator<Integer> it2 = l2.iterator();
while (it1.hasNext() && it2.hasNext()) {
it1.set(it1.next() + it2.next());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.