在 C# 中有效地将多个元素添加到列表的开头
本文关键字:添加 列表 开头 元素 有效地 | 更新日期: 2023-09-27 18:37:19
我有一个列表,我想在开头添加多个元素。添加到开始是线性时间,因为它由数组支持并且必须一次移动一个,如果我以天真的方式实现它,我无法承受多次执行此操作。
如果我确切地知道我要添加多少个元素,我是否可以将它们全部移动那么多,以便线性度只需要发生一次?
List<int> myList = new List<int> { 6, 7, 8, 9, 10 };
//Desired list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
//Unacceptable
for (int i = 5; i>=0; i--){
myList.Insert(0,i);
}
//Is this concept possible?
int newElements = 5;
for (int i = myList.Count; i>=0; i--){
myList[i+newElements] = myList[i];//This line is illegal, Index was out of range
}
for (int i = 0; i< newElements; i++){
myList[i] = i+1;
}
在此特定实例中,访问需要恒定时间,因此使用 List
.我需要能够尽快将元素添加到数据结构的开头和结尾。我对 O(m) 没问题,其中 m 是要添加的元素数(因为我认为这是无法避免的),但 O(m*n) 其中 n 是现有结构中的元素数太慢了。
您可以使用InsertRange
如果插入的集合实现ICollection<T>
,它将是线性的:
var newElements = new[] { 0, 1, 2, 3, 4 };
myList.InsertRange(0, newElements);
myList.InsertRange(0, new List<int> { 1, 2, 3, 4, 5 });
如果你的新元素已经在List
中,你可以使用List.AddRange
将你的"旧"列表添加到要添加的项目列表的末尾。
我想myList.InsertRange(0, newElements)
很适合你。Microsoft将使其尽可能高效。