[英]Efficiently adding multiple elements to the start of a List in C#
我有一個列表,希望將多個元素添加到開頭。 線性時間是增加時間的起點,因為它由數組支持並且必須一次移動一次,而且我負擔不起像我實現這種幼稚方式那樣需要執行的次數。
如果我確切知道要添加多少個元素,是否可以對它們全部進行移位,以使線性只需要發生一次?
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將使它盡可能高效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.