我有一個商品列表已按最高排名排序,我在變量topList中存儲。從另一個列表中查找列表中排名最高的項目
然後我有我存儲在變量currentList
的目標是找到誰是排名最高的topList currentList的元素項的當前列表。
[TestMethod]
public void MethodName14() {
var topList = new List<string>() {"AB", "DC", "ZG"}; // ordered by highest rank
var currentList = new List<string> {"ZG", "DC"};
var actual = ReturnTop(currentList, topList);
Assert.Equal("DC", actual); // because DC is in index 2 and ZG is in index 3
}
private string ReturnTop(List<string> currentList, List<string> topList) {
string result = null;
int index = 0;
foreach (var current in currentList) {
var lookupedCurrentIndex = topList.FindIndex(a => a == current);
if (index == 0) {
result = topList[index];
index = lookupedCurrentIndex;
} else {
if (lookupedCurrentIndex < index) {
index = lookupedCurrentIndex;
result = topList[index];
}
}
}
return result;
}
我的方法ReturnTop太慢了,它是O(n²)。我們可以做得更好嗎?
好像它可以縮短到'topList.Intersect(currentList).FirstOrDefault()'https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,ae06318d1f5fb355 – Slai
@Slai你說得對,謝謝! – dasblinkenlight