public int[] MaxSlidingWindow1(int[] nums, int k) { // SS: runtime complexity: O(n + n * log k) = O(n * log k) if (k == 1) { return(nums); } var result = new int[nums.Length - k + 1]; var resultIdx = 0; // SS: O(n) var maxHeap = new ModifiedMaxHeap(k); for (var i = 0; i < nums.Length; i++) { // SS: O(log k) maxHeap.Insert(nums[i]); if (maxHeap.Size() == k) { result[resultIdx++] = maxHeap.Top(); // SS: O(log k) maxHeap.Remove(nums[i - k + 1]); } } return(result); }
public void TestHeap1() { // Arrange var maxHeap = new ModifiedMaxHeap(3); // Act maxHeap.Insert(1); // Assert Assert.AreEqual(1, maxHeap.Top()); Assert.AreEqual(1, maxHeap.Size()); }
public void TestHeap2() { // Arrange var maxHeap = new ModifiedMaxHeap(5); maxHeap.Insert(1); maxHeap.Insert(2); maxHeap.Insert(3); // Act // Assert maxHeap.Remove(2); Assert.AreEqual(3, maxHeap.Top()); maxHeap.Remove(3); Assert.AreEqual(1, maxHeap.Size()); }