gpt4 book ai didi

c# - 使用 C# 将整数集转换为范围

转载 作者:太空狗 更新时间:2023-10-29 20:03:46 26 4
gpt4 key购买 nike

将一组整数转换为一组范围的最惯用的方法是什么?

例如给定集合 {0, 1, 2, 3, 4, 7, 8, 9, 11} 我想使用 C# 得到 { {0,4}, {7,9}, {11,11} }

此问题已在 C++ @ Solution in C++ 中得到解答

最佳答案

这不是很有效,但惯用的:

var nums = new HashSet<int>{0, 1, 2, 3, 4, 7, 8, 9, 11};
IEnumerable<Tuple<int, int>> ranges = Enumerable.Zip(
nums.Where(n => !nums.Contains(n - 1)),
nums.Where(n => !nums.Contains(n + 1)),
Tuple.Create);

效率更高,假设已排序:

public IEnumerable<Tuple<int, int>> GetContiguousRanges(IEnumerable<int> nums)
{
int start = nums.First();
int last = start - 1;
foreach (int i in nums)
{
if (i != last + 1)
{
yield return Tuple.Create(start, last);
start = i;
}
last = i;
}
yield return Tuple.Create(start, last);
}

关于c# - 使用 C# 将整数集转换为范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4147935/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com