Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/5007727ebacb9403326551d1d06a29fa to your computer and use it in GitHub Desktop.
Save jianminchen/5007727ebacb9403326551d1d06a29fa to your computer and use it in GitHub Desktop.
Leetcode 239 Sliding window maximum - using C# LinkedList as Dequeue.
public class Solution {
public int[] MaxSlidingWindow(int[] nums, int k) {
if (k == 0)
{
return nums; // julia: base case is added to pass online judge.
}
int length = nums.Length;
int numberOfSlidingWindow = length - k + 1;
var maximums = new int[numberOfSlidingWindow];
var linkedList = new LinkedList<int>(); // LinkedList acts like deque
for (int index = 0; index < length; index++)
{
var current = nums[index];
// Remove the first number in the queue if it falls out of the sliding window
if (linkedList.Count > 0 && linkedList.First.Value + k <= index)
{
linkedList.RemoveFirst();
}
// Visit the current number, remove from the tail of the
// queue indices if the value is smaller than the current number.
while (linkedList.Count > 0 && nums[linkedList.Last.Value] <= current)
{
linkedList.RemoveLast();
}
linkedList.AddLast(index);
// Set the max value in the window (always the top number in the queue)
int maximumsIndex = index + 1 - k;
if (maximumsIndex >= 0)
{
maximums[maximumsIndex] = nums[linkedList.First.Value];
}
}
return maximums;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment