【问题标题】:Efficient way to implement an indexed queue (where elements can be retrieved by index in O(1) time)?实现索引队列的有效方法(可以在 O(1) 时间内通过索引检索元素)?
【发布时间】:2011-10-12 14:03:51
【问题描述】:
【问题讨论】:
标签:
c#
.net
performance
indexing
queue
【解决方案1】:
您可以使用cyclic array。 IE。在数组中实现队列。
实现很简单,不需要使用外部库,自己实现即可。提示:使用m_beginIndex, m_nElements 成员比使用m_beginIndex, m_endIndex 更容易。
【解决方案2】:
public class IndexedQueue<T>
{
T[] array;
int start;
int len;
public IndexedQueue(int initialBufferSize)
{
array = new T[initialBufferSize];
start = 0;
len = 0;
}
public void Enqueue(T t)
{
if (len == array.Length)
{
//increase the size of the cicularBuffer, and copy everything
T[] bigger = new T[array.Length * 2];
for (int i = 0; i < len; i++)
{
bigger[i] = array[(start + i) % len];
}
start = 0;
array = bigger;
}
array[(start + len) % array.Length] = t;
++len;
}
public T Dequeue()
{
var result = array[start];
start = (start + 1) % array.Length;
--len;
return result;
}
public int Count { get { return len; } }
public T this[int index]
{
get
{
return array[(start + index) % array.Length];
}
}
}