我有一张地图清单 地图中的条目看起来像这样
{
key1:A;
key2:3;
key3:10;
}
{
key1:A;
key2:3;
key3:5;
}
{
key1:A;
key2:6;
key3:5;
}
{
key1:A;
key2:6;
key3:10;
}
key1 + key2生成一个复合键,列表中可以有一个或两个关于一个复合键的条目。
因此,如果列表中有多个条目,则必须使用值较小的条目。
如何在O(n)中解决这个问题。
答案 0 :(得分:0)
var ret = new List; // to contain resulting entries
var seen = new Set; // to keep track of what composite keys has been
// seen already (and, as such, included into the
// resulting list
foreach (inList as elt) { // iterate over the incoming list
if (!seen.has({key1: elt.key1, key2: elt.key2})) { // check key1,key2 composite key has already been seen
// append to `ret` list and mark as seen
seen.add({key1: elt.key1, key2: elt.key2});
ret.add(elt);
}
}
return ret; // return the result - assuming it's in a function body
时间复杂度为O(n)(假设List和Set附加操作为O(1)),空间复杂度为O(n)(约为传入列表大小的3倍)