首先在排序列表的開始處設置最大可能集。然後繼續從前面刪除值,直到下一個值適合,並在下一個值之後添加儘可能多的值。這使得一套新的。在任何特定時刻保持最大的跟蹤。
像這樣的東西在C#中:作爲
static IEnumerable<T[]> CloseSublists<T>(this IEnumerable<T> values, Func<T, T, bool> isClose) where T : IComparable<T> {
var window = new Queue<T>();
var enumerator = values.GetEnumerator();
if (!enumerator.MoveNext()) {
return;
}
bool more;
do {
window.Enqueue(enumerator.Current);
} while ((more = enumerator.MoveNext()) && isClose(window.Peek(), enumerator.Current));
yield return window.ToArray();
while (more) {
do {
window.Dequeue();
} while (window.Count != 0 && !isClose(window.Peek(), enumerator.Current));
do {
window.Enqueue(enumerator.Current);
} while ((more = enumerator.MoveNext()) && isClose(window.Peek(), enumerator.Current));
yield return window.ToArray();
}
}
和
public static T MaxBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> key) where TKey : IComparable<TKey> {
var enumerator = items.GetEnumerator();
enumerator.MoveNext();
var max = enumerator.Current;
TKey maxKey = key(max);
while (enumerator.MoveNext()) {
T current = enumerator.Current;
TKey currentKey = key(current);
int relation = currentKey.CompareTo(maxKey);
if (relation > 0) {
max = current;
maxKey = currentKey;
}
}
return max;
}
:
int[] x = {1, 2, 5, 6, 8, 9, 15};
x.CloseSublists((a, b) => b < a + 5).MaxBy(l => l.Length)
你怎麼downvote這麼快???我在不到10秒鐘之前就發佈了這個問題。我想你想看看我正在避免的示例代碼? – Evorlor
我將在本週晚些時候(和猶太年)工作。 同時看看:https://stackoverflow.com/questions/1624341/getting-pair-set-using-linq 與ConvertAll或Select功能一起使用。這將是醜陋的... – pashute