在LeetCode刷题,总是遇到优先队列解法,但是呢,c#并没有提供这种数据结构,没办法,只能自造一个PriorityQueue了
public class PriorityQueue<T>
{
IComparer<T> comparer;
SortedList<T, int> sList;
public int Count { get; private set; }
public PriorityQueue() : this(null) { }
public PriorityQueue( IComparer<T> comparer)
{
this.comparer = (comparer == null) ? Comparer<T>.Default : comparer;
this.sList = new SortedList<T, int>(this.comparer);
}
public void Push(T v)
{
if (sList.ContainsKey(v))
{
sList[v]++;
}
else
{
sList.Add(v, 1);
}
Count++;
}
public T Pop()
{
if (Count < 1) throw new InvalidOperationException("优先队列为空");
T first = sList.Keys[0];
if (--sList[first] < 1) sList.Remove(first);
Count--;
return first;
}
public T Peek()
{
if (Count < 1) throw new InvalidOperationException("优先队列为空");
return sList.Keys[0];
}
}
当然可以扩展方法,如果想从队尾取数据,把sList.Keys[0]
换成sList.Keys[sList.Keys.Count - 1]
就行了