Created
June 12, 2018 17:13
-
-
Save jianminchen/5007727ebacb9403326551d1d06a29fa to your computer and use it in GitHub Desktop.
Leetcode 239 Sliding window maximum - using C# LinkedList as Dequeue.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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