我可以直接在TDictionary类上创建TList吗?如果我用键创建我的TDictionary类,并且值总是与BlackList.Add(1,1)一样的数据,这看起来有点双重工作;
var
BlackList: TDictionary<Integer, Integer>;
ResultList: TDictionary<Integer, Integer>;
TestListA: TLIst<Integer>;
TestListB: TLIst<Integer>;
i: Integer;
begin
BlackList.Add(1, 1);
BlackList.Add(2, 2);
for i := 0 to TestListA.Count - 1 do
begin
if BlackList.ContainsValue(TestListA[i]) then
begin
// no action ...
end
else
begin
ResultList.Add(i, TestListA[i]);
end;
end;
for i := 0 to TestListB.Count - 1 do
begin
if BlackList.ContainsValue(TestListB[i]) then
begin
// no action ...
end
else
begin
if not(ResultList.ContainsValue(TestListB[i])) then
ResultList.Add(i, TestListB[i]);
end;
end;
end;该算法的目的是比较两个整数表,找出所有的双数,但从黑名单中排除数字。第一个Q在这里,Find common elements in two Integer List。
发布于 2014-02-02 08:19:48
在这个特定的代码中,使用TDictionary的全部目的是利用O(1)查找。对于TList (它是一个数组),您没有该属性。查找一般为O(n),如果排序为O(log n)。因此,您不能以任何方式从TList中提取O(1)查找性能,因此可以使用TDictionary。
因此,正是性能动机推动了TDictionary的使用。正如我在前面的问题中所说的,只有当列表很大时,设置字典的开销才是值得的。在这种情况下,您需要做一些基准来量化大型的含义。
至于您的字典,您使用的值并不重要,因为只有键是重要的。所以总是使用零。理想情况下,您需要的是基于与字典相同的算法的哈希集类型。但我不相信在RTL股票里有这样的东西。我希望像Spring4D这样的库提供这种功能。
https://stackoverflow.com/questions/21508400
复制相似问题