|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | + |
| 5 | +public class Solution |
| 6 | +{ |
| 7 | + public static void Main(string[] args) |
| 8 | + { |
| 9 | + int[] nums = { 7, 2, 4 }; |
| 10 | + |
| 11 | + //int[] result = MaxSlidingWindow(nums, 2); |
| 12 | + int[] result = MaxSlidingWindow2(nums, 2); |
| 13 | + |
| 14 | + Console.Write("[ "); |
| 15 | + foreach (int number in result) |
| 16 | + { |
| 17 | + Console.Write(number + ", "); |
| 18 | + } |
| 19 | + Console.WriteLine(" ]"); |
| 20 | + |
| 21 | + Console.ReadKey(); |
| 22 | + } |
| 23 | + |
| 24 | + #region Approach 1 brute force |
| 25 | + private static int _GetMaxInCollection(IEnumerable<int> collection) |
| 26 | + { |
| 27 | + if (collection == null || collection.Count() == 0) |
| 28 | + return 0; |
| 29 | + |
| 30 | + return collection.Max(); |
| 31 | + } |
| 32 | + |
| 33 | + public static int[] MaxSlidingWindow(int[] nums, int k) |
| 34 | + { |
| 35 | + if (nums == null || nums.Length == 0 || k == 0 || k > nums.Length) |
| 36 | + return null; |
| 37 | + |
| 38 | + if (k == 1) |
| 39 | + return nums; |
| 40 | + |
| 41 | + List<int> result = new List<int>(); |
| 42 | + |
| 43 | + for (int i = 0; i < nums.Length; i++) |
| 44 | + { |
| 45 | + if (i + k > nums.Length) |
| 46 | + { |
| 47 | + break; |
| 48 | + } |
| 49 | + |
| 50 | + int maxNumber = _GetMaxInCollection(nums.Skip(i).Take(k)); |
| 51 | + result.Add(maxNumber); |
| 52 | + } |
| 53 | + |
| 54 | + return result.ToArray(); |
| 55 | + } |
| 56 | + #endregion |
| 57 | + |
| 58 | + #region Approach 2 |
| 59 | + public static int[] MaxSlidingWindow2(int[] nums, int k) |
| 60 | + { |
| 61 | + if (nums == null || nums.Length == 0 || k == 0 || k > nums.Length) |
| 62 | + return null; |
| 63 | + |
| 64 | + if (k == 1) |
| 65 | + return nums; |
| 66 | + |
| 67 | + List<int> result = new List<int>(); |
| 68 | + LinkedList<int> queue = new LinkedList<int>(); |
| 69 | + int left = 0, right = 0; |
| 70 | + |
| 71 | + while (right < nums.Length) |
| 72 | + { |
| 73 | + // pop smaller values from queue |
| 74 | + while (queue.Count > 0 && nums[queue.Last.Value] < nums[right]) |
| 75 | + queue.RemoveLast(); |
| 76 | + queue.AddLast(right); |
| 77 | + |
| 78 | + // remove left val from the window |
| 79 | + if (left > queue.First.Value) |
| 80 | + queue.RemoveFirst(); |
| 81 | + |
| 82 | + if (right + 1 >= k) |
| 83 | + { |
| 84 | + result.Add(nums[queue.First.Value]); |
| 85 | + left++; |
| 86 | + } |
| 87 | + |
| 88 | + right++; |
| 89 | + } |
| 90 | + |
| 91 | + return result.ToArray(); |
| 92 | + } |
| 93 | + #endregion |
| 94 | +} |
| 95 | + |
0 commit comments