c# – 高效滚动最大和最小窗口

前端之家收集整理的这篇文章主要介绍了c# – 高效滚动最大和最小窗口前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想有效地计算滚动的最大值和最小值.比每次窗口移动时重新计算所有使用值中的最大值/最小值更好.

这里有一篇文章提出了同样的问题,并且有人发布了一个涉及某种堆栈方法解决方案,据说根据其评级工作.但是,对于我的生活,我再也找不到它.

在寻找解决方案或帖子时,我们将不胜感激.谢谢你们!

解决方法@H_404_8@
您要使用的算法称为升序最小值 (C++ implementation).

要在C#中执行此操作,您将需要获得double ended queue类,并且在NuGet上以名称Nito.Deque存在一个好类.

我已经使用Nito.Deque编写了一个快速的C#实现,但我只是简单地检查了它,并且从头开始做了所以它可能是错的!

  1. public static class AscendingMinima
  2. {
  3. private struct MinimaValue
  4. {
  5. public int RemoveIndex { get; set; }
  6. public double Value { get; set; }
  7. }
  8.  
  9. public static double[] GetMin(this double[] input,int window)
  10. {
  11. var queue = new Deque<MinimaValue>();
  12. var result = new double[input.Length];
  13.  
  14. for (int i = 0; i < input.Length; i++)
  15. {
  16. var val = input[i];
  17.  
  18. // Note: in Nito.Deque,queue[0] is the front
  19. while (queue.Count > 0 && i >= queue[0].RemoveIndex)
  20. queue.RemoveFromFront();
  21.  
  22. while (queue.Count > 0 && queue[queue.Count - 1].Value >= val)
  23. queue.RemoveFromBack();
  24.  
  25. queue.AddToBack(new MinimaValue{RemoveIndex = i + window,Value = val });
  26.  
  27. result[i] = queue[0].Value;
  28. }
  29.  
  30. return result;
  31. }
  32. }

猜你在找的C#相关文章