您想使用 XY 对的排序列表(List<Tuple<double,double>>
这将是合适的类型)。假设您有两个输入列表 series1 和 series2,它们按 X 值排序,并且您正在检查 series2(并且可能是插值)以查找 series1 中存在的 X 值(正如您在问题中所述)。因为您需要检查 series1 中的每个坐标,所以最小复杂度为 O(n)。
保持这种效率的关键是列表是有序的,这意味着您不必在整个 series2 列表中搜索 series1 中的每个 X 值。为此,您可以保留指向 series2 中当前项目的指针,并在遍历 series1 时移动它。这是伪 C# 来说明我的意思。
var s2idx = 0;
foreach(s1 in series1)
{
// go forward through series2 until you find the next interp target
while(series2[s2dix].Item1 < s1.Item1 && s2idx < series2.Length)
s2idx++;
if(s2idx == series2.Length)
// all s1 Xs are > the biggest s2 X, so just add the rest of the s1 points to your output
// or whatever else you want to do, then quit the foreach loop
var s2 = series2[s2idx];
if(s1.Item1 == s2.Item1)
// Xs are equal, handle this case as you like
else
// calculate the interpolated point and put it in your output
}
我已经使用数组列表展示了这一点,但是您可以使用链表同样有效地做到这一点;只需使用“当前”指针来跟踪您在 series2 中的位置而不是索引。
这里的复杂性是 O(m + n),因为您每个列表都遍历一次(在最坏和 [最可能] 平均情况下)。最好的情况是 O(n),但这只会发生在退化的实例中(所有 series1 X 值都大于最小的 series2 X 值,或者 series2 为空)。请记住,这需要对两个列表进行排序,因此您正在查看 O(m + n + m log m + n log n) 全部内容。请注意,这种复杂性主要由排序成本决定,这意味着它非常有效。