Advertisement
Guest User

Untitled

a guest
Jul 31st, 2015
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. // Given a sequence of integers and a size k,
  5. // print the minimum number for every sliding window of size k
  6.  
  7. namespace SlidingMinimum
  8. {
  9. public class Program
  10. {
  11. public static void Main(string[] args)
  12. {
  13. // test(new int[]{4, 5, 1, 7, 3, -1, 2}, 2);
  14. test(new int[]{1, 2, 3, 1, 2, 3}, 3);
  15. }
  16.  
  17. static void test(int[] arr, int k) {
  18. printSlidingMinimum(arr, k);
  19. }
  20.  
  21. // Asssumes k > 1
  22. static void printSlidingMinimum(int[] arr, int k) {
  23. if (k < 1) {
  24. Console.WriteLine("k should be greater than 1");
  25. return;
  26. }
  27.  
  28. var minQueue = new Queue<int>();
  29.  
  30. bool shouldPrintMinimum = false;
  31.  
  32. minQueue.Enqueue(arr[0]);
  33.  
  34. for(int i = 1; i < arr.Length; i++) {
  35. if (i == k - 1) {
  36. shouldPrintMinimum = true;
  37. }
  38.  
  39. var current = arr[i];
  40.  
  41. if (minQueue.Count == k) {
  42. var dequeuedValue = minQueue.Dequeue();
  43. }
  44.  
  45. if (current < minQueue.Peek()) {
  46. while (minQueue.Count > 0) {
  47. var dequeuedValue = minQueue.Dequeue();
  48. }
  49. }
  50.  
  51. minQueue.Enqueue(current);
  52.  
  53. if (shouldPrintMinimum) {
  54. Console.WriteLine(minQueue.Peek());
  55. }
  56. }
  57. }
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement