在 C# 中,
给定以下整数数组,例如100001100002100005100006100007100009100011
我想生成一个包含以下值的数据结构
[0] => {Type= "Continuous", Count=2, Items = [100001, 100002]}
[1] => {Type= "Continuous", Count=3, Items = [100005, 100006, 100007]}
[2] => {Type= "Individual", Count=2, Items = [100008, 100011]}
数据结构并不重要。我正在寻找一种以这种方式对整数进行分组的算法。
假设您的整数数组已排序:
class MyGroup
{
public string Type => (Numbers?.Count??0) == 1? "Individual" : "Continuous";
public List<int> Numbers;
public int Count => Numbers.Count;
}
List<MyGroup> LST = new List<MyGroup>();
List<int> Temp = new List<int>();
//Run from 0 to second-last element (arr is your array)
for (int i = 0; i < arr.Length - 1; i++)
{
Temp.Add(arr[i]); //add this number to current group's list
if (arr[i + 1] != arr[i] + 1) //if next number is not adjacent
{
LST.Add(new MyGroup() { Numbers = Temp }); //create a new group
Temp = new List<int>(); //and a new current list
}
}
LST.Add(new MyGroup() { Numbers = Temp }); //create a new group
//The above loop exits before the last item of the array.
//Here we simply check if it is adjacent, we add it to the last group.
//otherwise we create a new group for it.
if (arr[arr.Length - 1] == arr[arr.Length - 2] + 1)
LST.Last().Numbers.Add(arr.Last());
else
LST.Add(new MyGroup() { Numbers = new List<int>(new[] { arr.Last() }) });
这是一个解决方案:
class Group
{
public int StartIndex { get; set; }
public int EndIndex { get; set; }
public int Length { get { return EndIndex - StartIndex; } }
public override string ToString()
{
return $"{StartIndex}-{EndIndex}";
}
}
然后
static List<Group> FindGroups(int[] intArray)
{
List<Group> groups = new List<Group>();
int tempStartIndex = 0;
for (int i = 1; i < intArray.Length; i++)
{
var value = intArray[i] - intArray[i - 1] == 1 ? 0 : 1;
if (value == 1)
{
groups.Add(new Group() { StartIndex = tempStartIndex, EndIndex = i - 1 });
tempStartIndex = i;
}
}
if (groups[groups.Count - 1].EndIndex != intArray.Length)
{
groups.Add(new Group() { StartIndex = tempStartIndex, EndIndex = intArray.Length - 1 });
}
return groups;
}