LeetCode problem 239. Sliding Window Maximum
You are given an array of integers
nums
, there is a sliding window of sizek
which is moving from the very left of the array to the very right. You can only see thek
numbers in the window. Each time the sliding window moves right by one position.Return the max sliding window.
Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7
Constraints:
• 1 <= nums.length <= 105
• -104 <= nums[i] <= 104
• 1 <= k <= nums.length
There is the brute force approach which runs at O(n*k) with 2 loops and surprisingly that got accepted on LeetCode when I was expecting a time out exception, however the run time faster than just 5% of the rest of the submissions.
After doing some research, I came across the deque (deck) approach which is said to be linear time and so I implemented a version using a swift array. The run time improved, however, it still said my submission was faster than only half of the other submissions which is fine, however, I expected this solution to do better since it improves from O(n*k) to O(n) and was suggested as one of the best solutions. Here are my results:
So my question is, can my code be improved / optimize further in terms of run time or is my assumption above wrong ?
func maxSlidingWindowDeque(_ nums: [Int], _ k: Int) -> [Int]
{
if nums.count <= 1
{
return nums
}
var maxArray: [Int] = []
var deque: [Int] = []
for index in 0 ..< k
{
while !deque.isEmpty
{
if let lastIndex = deque.last,
nums[index] > nums[lastIndex]
{
deque.removeLast()
continue
}
break
}
deque.append(index)
}
for endIndex in k ..< nums.count
{
let currentMaxIndex = deque[0]
maxArray.append(nums[currentMaxIndex])
if !deque.isEmpty && deque[0] < (endIndex - k) + 1
{
deque.removeFirst()
}
while !deque.isEmpty
{
if let lastIndexInDeque = deque.last, nums[endIndex] >= nums[lastIndexInDeque]
{
deque.removeLast()
continue
}
break
}
deque.append(endIndex)
}
if !deque.isEmpty
{
let maxValueIndex = deque[0]
maxArray.append(nums[maxValueIndex])
}
return maxArray
}
reserveCapacity
of themaxArray
given you know how long that array is going to be. \$\endgroup\$