ดังนั้นแล้วทำไมเจ้าจะไม่สุขด้วยตอบกลับก่อนการเกิดขึ้นอีกของ"เลื่อน"? เพราะหลังจากนั้นในห้องลำดับคุณดูเหมือนคำว่า"เลื่อน"อีกครั้ง ทำไมคุณถึงคืนก่อนการเกิดขึ้นอีกขอ"ร"? เพราะหลังจากนั้นในห้องลำดับคุณไม่เห็นคำนี้อีกต่อไปแล้ว
ดังนั้น:คืลาสักครู่คำสั่งใหม่ของที่เหลือของลำดับไม่มีคำพูด
มันจะเป็นเรื่องง่ายเลยสำหรับ LINQ กับ recursion แต่มันไม่ใช่ประสิทธิภาพ:สำหรับทุกคำที่คุณจะต้องเช็คที่เหลือของลำดับที่จะเห็นถ้าคำในส่วนที่เหลือ
มันจะเป็นทางที่มีประสิทธิภาพเพื่อจำได้สูงสุดดัชนีใหคุณเจอสักคำ
เป็นส่วนขยายวิธีการ. ถ้าคุณยังไม่คุ้นเคยกับส่วนขยายวิธีการของเห็น ส่วนขยายวิธีการของ demystified.
private static IEnumerable<T> FindLastOccurences<T>(this IEnumerable<T> source)
{
return FindLastOccurrences<T>(source, null);
}
private static IEnumerable<T> FindLastOccurences<T>(this IEnumerable<T> source,
IEqualityComparer<T> comparer)
{
// TODO: check source not null
if (comparer == null) comparer = EqualityComparer<T>.Default;
Dictionary<T, int> dictionary = new Dictionary<T, int>(comparer);
int index = 0;
foreach (T item in source)
{
// did we already see this T? = is this in the dictionary
if (dictionary.TryGetValue(item, out int highestIndex))
{
// we already saw it at index highestIndex.
dictionary[item] = index;
}
else
{
// it is not in the dictionary, we never saw this item.
dictionary.Add(item, index);
}
++index;
}
// return the keys after sorting by value (which contains the highest index)
return dictionay.OrderBy(keyValuePair => keyValuePair.Value)
.Select(keyValuePair => keyValuePair.Key);
}
ดังนั้นสำหรับทุกรายการอยู่ในแหล่งลำดับเราตรวจสอบว่ามันอยู่ในพจนานุกรมแล้ว ถ้าไม่เราเพิ่มรายการเป็นกุญแจให้พจนานุกรมแล้ว คืนค่าระดัชนี
ถ้ามันเป็นอยู่แล้วอยู่ในพจนานุกรมจากนั้นก็มีค่าสูงสุดดัชนีของที่เราเจอรายการนี้มาก่อน เห็นได้ชัดว่าระดัชนีปัจจุบันคือสูงขึ้นดังนั้นเราแทนที่ค่าในพจนานุกรม
ในที่สุดเราสั่งซื้อกุญแจค่าเหลืออยู่ในพจนานุกรมโดยการส่งจดหมายค่าและคืนเดียวที่กุญแจ