diff --git a/solution/0200-0299/0239.Sliding Window Maximum/README.md b/solution/0200-0299/0239.Sliding Window Maximum/README.md index fed5907c2b121..6ebec340295bf 100644 --- a/solution/0200-0299/0239.Sliding Window Maximum/README.md +++ b/solution/0200-0299/0239.Sliding Window Maximum/README.md @@ -171,100 +171,6 @@ func (h *hp) Push(v any) { *h = append(*h, v.(pair)) } func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v } ``` -#### Rust - -```rust -use std::collections::VecDeque; - -impl Solution { - #[allow(dead_code)] - pub fn max_sliding_window(nums: Vec, k: i32) -> Vec { - // The deque contains the index of `nums` - let mut q: VecDeque = VecDeque::new(); - let mut ans_vec: Vec = Vec::new(); - - for i in 0..nums.len() { - // Check the first element of queue, if it's out of bound - if !q.is_empty() && (i as i32) - k + 1 > (*q.front().unwrap() as i32) { - // Pop it out - q.pop_front(); - } - // Pop back elements out until either the deque is empty - // Or the back element is greater than the current traversed element - while !q.is_empty() && nums[*q.back().unwrap()] <= nums[i] { - q.pop_back(); - } - // Push the current index in queue - q.push_back(i); - // Check if the condition is satisfied - if i >= ((k - 1) as usize) { - ans_vec.push(nums[*q.front().unwrap()]); - } - } - - ans_vec - } -} -``` - -#### JavaScript - -```js -/** - * @param {number[]} nums - * @param {number} k - * @return {number[]} - */ -var maxSlidingWindow = function (nums, k) { - let ans = []; - let q = []; - for (let i = 0; i < nums.length; ++i) { - if (q && i - k + 1 > q[0]) { - q.shift(); - } - while (q && nums[q[q.length - 1]] <= nums[i]) { - q.pop(); - } - q.push(i); - if (i >= k - 1) { - ans.push(nums[q[0]]); - } - } - return ans; -}; -``` - -#### C# - -```cs -using System.Collections.Generic; - -public class Solution { - public int[] MaxSlidingWindow(int[] nums, int k) { - if (nums.Length == 0) return new int[0]; - var result = new int[nums.Length - k + 1]; - var descOrderNums = new LinkedList(); - for (var i = 0; i < nums.Length; ++i) - { - if (i >= k && nums[i - k] == descOrderNums.First.Value) - { - descOrderNums.RemoveFirst(); - } - while (descOrderNums.Count > 0 && nums[i] > descOrderNums.Last.Value) - { - descOrderNums.RemoveLast(); - } - descOrderNums.AddLast(nums[i]); - if (i >= k - 1) - { - result[i - k + 1] = descOrderNums.First.Value; - } - } - return result; - } -} -``` - @@ -273,20 +179,11 @@ public class Solution { ### 方法二:单调队列 -这道题也可以使用单调队列来解决。时间复杂度 $O(n)$,空间复杂度 $O(k)$。 +求滑动窗口的最大值,一种常见的方法是使用单调队列。 -单调队列常见模型:找出滑动窗口中的最大值/最小值。模板: +我们可以维护一个从队头到队尾单调递减的队列 $q$,队列中存储的是元素的下标。遍历数组 $\textit{nums}$,对于当前元素 $\textit{nums}[i]$,我们首先判断队头元素是否滑出窗口,如果滑出窗口则将队头元素弹出。然后我们将当前元素 $\textit{nums}[i]$ 从队尾开始依次与队尾元素比较,如果队尾元素小于等于当前元素,则将队尾元素弹出,直到队尾元素大于当前元素或者队列为空。然后将当前元素的下标加入队列。此时队列的队头元素即为当前滑动窗口的最大值,注意,我们将队头元素加入结果数组的时机是当下标 $i$ 大于等于 $k-1$ 时。 -```python -q = deque() -for i in range(n): - # 判断队头是否滑出窗口 - while q and checkout_out(q[0]): - q.popleft() - while q and check(q[-1]): - q.pop() - q.append(i) -``` +时间复杂度 $O(n)$,空间复杂度 $O(k)$。其中 $n$ 为数组 $\textit{nums}$ 的长度。 @@ -297,10 +194,10 @@ class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: q = deque() ans = [] - for i, v in enumerate(nums): - if q and i - k + 1 > q[0]: + for i, x in enumerate(nums): + if q and i - q[0] >= k: q.popleft() - while q and nums[q[-1]] <= v: + while q and nums[q[-1]] <= x: q.pop() q.append(i) if i >= k - 1: @@ -316,16 +213,16 @@ class Solution { int n = nums.length; int[] ans = new int[n - k + 1]; Deque q = new ArrayDeque<>(); - for (int i = 0, j = 0; i < n; ++i) { - if (!q.isEmpty() && i - k + 1 > q.peekFirst()) { + for (int i = 0; i < n; ++i) { + if (!q.isEmpty() && i - q.peekFirst() >= k) { q.pollFirst(); } while (!q.isEmpty() && nums[q.peekLast()] <= nums[i]) { q.pollLast(); } - q.offer(i); + q.offerLast(i); if (i >= k - 1) { - ans[j++] = nums[q.peekFirst()]; + ans[i - k + 1] = nums[q.peekFirst()]; } } return ans; @@ -342,15 +239,15 @@ public: deque q; vector ans; for (int i = 0; i < nums.size(); ++i) { - if (!q.empty() && i - k + 1 > q.front()) { + if (q.size() && i - q.front() >= k) { q.pop_front(); } - while (!q.empty() && nums[q.back()] <= nums[i]) { + while (q.size() && nums[q.back()] <= nums[i]) { q.pop_back(); } q.push_back(i); if (i >= k - 1) { - ans.emplace_back(nums[q.front()]); + ans.push_back(nums[q.front()]); } } return ans; @@ -363,11 +260,11 @@ public: ```go func maxSlidingWindow(nums []int, k int) (ans []int) { q := []int{} - for i, v := range nums { - if len(q) > 0 && i-k+1 > q[0] { + for i, x := range nums { + if len(q) > 0 && i-q[0] >= k { q = q[1:] } - for len(q) > 0 && nums[q[len(q)-1]] <= v { + for len(q) > 0 && nums[q[len(q)-1]] <= x { q = q[:len(q)-1] } q = append(q, i) @@ -375,10 +272,93 @@ func maxSlidingWindow(nums []int, k int) (ans []int) { ans = append(ans, nums[q[0]]) } } - return ans + return +} +``` + +#### TypeScript + +```ts +function maxSlidingWindow(nums: number[], k: number): number[] { + const ans: number[] = []; + const q = new Deque(); + for (let i = 0; i < nums.length; ++i) { + if (!q.isEmpty() && i - q.front()! >= k) { + q.popFront(); + } + while (!q.isEmpty() && nums[q.back()!] <= nums[i]) { + q.popBack(); + } + q.pushBack(i); + if (i >= k - 1) { + ans.push(nums[q.front()!]); + } + } + return ans; +} +``` + +#### Rust + +```rust +use std::collections::VecDeque; + +impl Solution { + pub fn max_sliding_window(nums: Vec, k: i32) -> Vec { + let k = k as usize; + let mut ans = Vec::new(); + let mut q: VecDeque = VecDeque::new(); + + for i in 0..nums.len() { + if let Some(&front) = q.front() { + if i >= front + k { + q.pop_front(); + } + } + while let Some(&back) = q.back() { + if nums[back] <= nums[i] { + q.pop_back(); + } else { + break; + } + } + q.push_back(i); + if i >= k - 1 { + ans.push(nums[*q.front().unwrap()]); + } + } + ans + } } ``` +#### JavaScript + +```js +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var maxSlidingWindow = function (nums, k) { + const ans = []; + const q = new Deque(); + for (let i = 0; i < nums.length; ++i) { + if (!q.isEmpty() && i - q.front() >= k) { + q.popFront(); + } + while (!q.isEmpty() && nums[q.back()] <= nums[i]) { + q.popBack(); + } + q.pushBack(i); + if (i >= k - 1) { + ans.push(nums[q.front()]); + } + } + return ans; +}; +``` + diff --git a/solution/0200-0299/0239.Sliding Window Maximum/README_EN.md b/solution/0200-0299/0239.Sliding Window Maximum/README_EN.md index 9825d89ad0e11..112d6692a691a 100644 --- a/solution/0200-0299/0239.Sliding Window Maximum/README_EN.md +++ b/solution/0200-0299/0239.Sliding Window Maximum/README_EN.md @@ -30,7 +30,7 @@ tags:
 Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
 Output: [3,3,5,5,6,7]
-Explanation: 
+Explanation:
 Window position                Max
 ---------------               -----
 [1  3  -1] -3  5  3  6  7       3
@@ -63,7 +63,13 @@ Window position                Max
 
 
 
-### Solution 1
+### Solution 1: Priority Queue (Max-Heap)
+
+We can use a priority queue (max-heap) to maintain the maximum value in the sliding window.
+
+First, add the first $k-1$ elements to the priority queue. Then, starting from the $k$-th element, add the new element to the priority queue and check if the top element of the heap is out of the window. If it is, remove the top element. Then, add the top element of the heap to the result array.
+
+The time complexity is $O(n \times \log k)$, and the space complexity is $O(k)$. Here, $n$ is the length of the array.
 
 
 
@@ -163,107 +169,19 @@ func (h *hp) Push(v any)   { *h = append(*h, v.(pair)) }
 func (h *hp) Pop() any     { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
 ```
 
-#### Rust
-
-```rust
-use std::collections::VecDeque;
-
-impl Solution {
-    #[allow(dead_code)]
-    pub fn max_sliding_window(nums: Vec, k: i32) -> Vec {
-        // The deque contains the index of `nums`
-        let mut q: VecDeque = VecDeque::new();
-        let mut ans_vec: Vec = Vec::new();
-
-        for i in 0..nums.len() {
-            // Check the first element of queue, if it's out of bound
-            if !q.is_empty() && (i as i32) - k + 1 > (*q.front().unwrap() as i32) {
-                // Pop it out
-                q.pop_front();
-            }
-            // Pop back elements out until either the deque is empty
-            // Or the back element is greater than the current traversed element
-            while !q.is_empty() && nums[*q.back().unwrap()] <= nums[i] {
-                q.pop_back();
-            }
-            // Push the current index in queue
-            q.push_back(i);
-            // Check if the condition is satisfied
-            if i >= ((k - 1) as usize) {
-                ans_vec.push(nums[*q.front().unwrap()]);
-            }
-        }
-
-        ans_vec
-    }
-}
-```
-
-#### JavaScript
-
-```js
-/**
- * @param {number[]} nums
- * @param {number} k
- * @return {number[]}
- */
-var maxSlidingWindow = function (nums, k) {
-    let ans = [];
-    let q = [];
-    for (let i = 0; i < nums.length; ++i) {
-        if (q && i - k + 1 > q[0]) {
-            q.shift();
-        }
-        while (q && nums[q[q.length - 1]] <= nums[i]) {
-            q.pop();
-        }
-        q.push(i);
-        if (i >= k - 1) {
-            ans.push(nums[q[0]]);
-        }
-    }
-    return ans;
-};
-```
-
-#### C#
-
-```cs
-using System.Collections.Generic;
-
-public class Solution {
-    public int[] MaxSlidingWindow(int[] nums, int k) {
-        if (nums.Length == 0) return new int[0];
-        var result = new int[nums.Length - k + 1];
-        var descOrderNums = new LinkedList();
-        for (var i = 0; i < nums.Length; ++i)
-        {
-            if (i >= k && nums[i - k] == descOrderNums.First.Value)
-            {
-                descOrderNums.RemoveFirst();
-            }
-            while (descOrderNums.Count > 0 && nums[i] > descOrderNums.Last.Value)
-            {
-                descOrderNums.RemoveLast();
-            }
-            descOrderNums.AddLast(nums[i]);
-            if (i >= k - 1)
-            {
-                result[i - k + 1] = descOrderNums.First.Value;
-            }
-        }
-        return result;
-    }
-}
-```
-
 
 
 
 
 
 
-### Solution 2
+### Solution 2: Monotonic Queue
+
+To find the maximum value in a sliding window, a common method is to use a monotonic queue.
+
+We can maintain a queue $q$ that is monotonically decreasing from the front to the back, storing the indices of the elements. As we traverse the array $\textit{nums}$, for the current element $\textit{nums}[i]$, we first check if the front element of the queue is out of the window. If it is, we remove the front element. Then, we compare the current element $\textit{nums}[i]$ with the elements at the back of the queue. If the elements at the back are less than or equal to the current element, we remove them until the element at the back is greater than the current element or the queue is empty. Then, we add the index of the current element to the queue. At this point, the front element of the queue is the maximum value of the current sliding window. Note that we add the front element of the queue to the result array when the index $i$ is greater than or equal to $k-1$.
+
+The time complexity is $O(n)$, and the space complexity is $O(k)$. Here, $n$ is the length of the array $\textit{nums}$.
 
 
 
@@ -274,10 +192,10 @@ class Solution:
     def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
         q = deque()
         ans = []
-        for i, v in enumerate(nums):
-            if q and i - k + 1 > q[0]:
+        for i, x in enumerate(nums):
+            if q and i - q[0] >= k:
                 q.popleft()
-            while q and nums[q[-1]] <= v:
+            while q and nums[q[-1]] <= x:
                 q.pop()
             q.append(i)
             if i >= k - 1:
@@ -293,16 +211,16 @@ class Solution {
         int n = nums.length;
         int[] ans = new int[n - k + 1];
         Deque q = new ArrayDeque<>();
-        for (int i = 0, j = 0; i < n; ++i) {
-            if (!q.isEmpty() && i - k + 1 > q.peekFirst()) {
+        for (int i = 0; i < n; ++i) {
+            if (!q.isEmpty() && i - q.peekFirst() >= k) {
                 q.pollFirst();
             }
             while (!q.isEmpty() && nums[q.peekLast()] <= nums[i]) {
                 q.pollLast();
             }
-            q.offer(i);
+            q.offerLast(i);
             if (i >= k - 1) {
-                ans[j++] = nums[q.peekFirst()];
+                ans[i - k + 1] = nums[q.peekFirst()];
             }
         }
         return ans;
@@ -319,15 +237,15 @@ public:
         deque q;
         vector ans;
         for (int i = 0; i < nums.size(); ++i) {
-            if (!q.empty() && i - k + 1 > q.front()) {
+            if (q.size() && i - q.front() >= k) {
                 q.pop_front();
             }
-            while (!q.empty() && nums[q.back()] <= nums[i]) {
+            while (q.size() && nums[q.back()] <= nums[i]) {
                 q.pop_back();
             }
             q.push_back(i);
             if (i >= k - 1) {
-                ans.emplace_back(nums[q.front()]);
+                ans.push_back(nums[q.front()]);
             }
         }
         return ans;
@@ -340,11 +258,11 @@ public:
 ```go
 func maxSlidingWindow(nums []int, k int) (ans []int) {
 	q := []int{}
-	for i, v := range nums {
-		if len(q) > 0 && i-k+1 > q[0] {
+	for i, x := range nums {
+		if len(q) > 0 && i-q[0] >= k {
 			q = q[1:]
 		}
-		for len(q) > 0 && nums[q[len(q)-1]] <= v {
+		for len(q) > 0 && nums[q[len(q)-1]] <= x {
 			q = q[:len(q)-1]
 		}
 		q = append(q, i)
@@ -352,10 +270,93 @@ func maxSlidingWindow(nums []int, k int) (ans []int) {
 			ans = append(ans, nums[q[0]])
 		}
 	}
-	return ans
+	return
+}
+```
+
+#### TypeScript
+
+```ts
+function maxSlidingWindow(nums: number[], k: number): number[] {
+    const ans: number[] = [];
+    const q = new Deque();
+    for (let i = 0; i < nums.length; ++i) {
+        if (!q.isEmpty() && i - q.front()! >= k) {
+            q.popFront();
+        }
+        while (!q.isEmpty() && nums[q.back()!] <= nums[i]) {
+            q.popBack();
+        }
+        q.pushBack(i);
+        if (i >= k - 1) {
+            ans.push(nums[q.front()!]);
+        }
+    }
+    return ans;
+}
+```
+
+#### Rust
+
+```rust
+use std::collections::VecDeque;
+
+impl Solution {
+    pub fn max_sliding_window(nums: Vec, k: i32) -> Vec {
+        let k = k as usize;
+        let mut ans = Vec::new();
+        let mut q: VecDeque = VecDeque::new();
+
+        for i in 0..nums.len() {
+            if let Some(&front) = q.front() {
+                if i >= front + k {
+                    q.pop_front();
+                }
+            }
+            while let Some(&back) = q.back() {
+                if nums[back] <= nums[i] {
+                    q.pop_back();
+                } else {
+                    break;
+                }
+            }
+            q.push_back(i);
+            if i >= k - 1 {
+                ans.push(nums[*q.front().unwrap()]);
+            }
+        }
+        ans
+    }
 }
 ```
 
+#### JavaScript
+
+```js
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number[]}
+ */
+var maxSlidingWindow = function (nums, k) {
+    const ans = [];
+    const q = new Deque();
+    for (let i = 0; i < nums.length; ++i) {
+        if (!q.isEmpty() && i - q.front() >= k) {
+            q.popFront();
+        }
+        while (!q.isEmpty() && nums[q.back()] <= nums[i]) {
+            q.popBack();
+        }
+        q.pushBack(i);
+        if (i >= k - 1) {
+            ans.push(nums[q.front()]);
+        }
+    }
+    return ans;
+};
+```
+
 
 
 
diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution.cs b/solution/0200-0299/0239.Sliding Window Maximum/Solution.cs
deleted file mode 100644
index 15052452592c9..0000000000000
--- a/solution/0200-0299/0239.Sliding Window Maximum/Solution.cs	
+++ /dev/null
@@ -1,26 +0,0 @@
-using System.Collections.Generic;
-
-public class Solution {
-    public int[] MaxSlidingWindow(int[] nums, int k) {
-        if (nums.Length == 0) return new int[0];
-        var result = new int[nums.Length - k + 1];
-        var descOrderNums = new LinkedList();
-        for (var i = 0; i < nums.Length; ++i)
-        {
-            if (i >= k && nums[i - k] == descOrderNums.First.Value)
-            {
-                descOrderNums.RemoveFirst();
-            }
-            while (descOrderNums.Count > 0 && nums[i] > descOrderNums.Last.Value)
-            {
-                descOrderNums.RemoveLast();
-            }
-            descOrderNums.AddLast(nums[i]);
-            if (i >= k - 1)
-            {
-                result[i - k + 1] = descOrderNums.First.Value;
-            }
-        }
-        return result;
-    }
-}
\ No newline at end of file
diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution.js b/solution/0200-0299/0239.Sliding Window Maximum/Solution.js
deleted file mode 100644
index f90d4438611d4..0000000000000
--- a/solution/0200-0299/0239.Sliding Window Maximum/Solution.js	
+++ /dev/null
@@ -1,22 +0,0 @@
-/**
- * @param {number[]} nums
- * @param {number} k
- * @return {number[]}
- */
-var maxSlidingWindow = function (nums, k) {
-    let ans = [];
-    let q = [];
-    for (let i = 0; i < nums.length; ++i) {
-        if (q && i - k + 1 > q[0]) {
-            q.shift();
-        }
-        while (q && nums[q[q.length - 1]] <= nums[i]) {
-            q.pop();
-        }
-        q.push(i);
-        if (i >= k - 1) {
-            ans.push(nums[q[0]]);
-        }
-    }
-    return ans;
-};
diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution.rs b/solution/0200-0299/0239.Sliding Window Maximum/Solution.rs
deleted file mode 100644
index dd27b35cc9810..0000000000000
--- a/solution/0200-0299/0239.Sliding Window Maximum/Solution.rs	
+++ /dev/null
@@ -1,31 +0,0 @@
-use std::collections::VecDeque;
-
-impl Solution {
-    #[allow(dead_code)]
-    pub fn max_sliding_window(nums: Vec, k: i32) -> Vec {
-        // The deque contains the index of `nums`
-        let mut q: VecDeque = VecDeque::new();
-        let mut ans_vec: Vec = Vec::new();
-
-        for i in 0..nums.len() {
-            // Check the first element of queue, if it's out of bound
-            if !q.is_empty() && (i as i32) - k + 1 > (*q.front().unwrap() as i32) {
-                // Pop it out
-                q.pop_front();
-            }
-            // Pop back elements out until either the deque is empty
-            // Or the back element is greater than the current traversed element
-            while !q.is_empty() && nums[*q.back().unwrap()] <= nums[i] {
-                q.pop_back();
-            }
-            // Push the current index in queue
-            q.push_back(i);
-            // Check if the condition is satisfied
-            if i >= ((k - 1) as usize) {
-                ans_vec.push(nums[*q.front().unwrap()]);
-            }
-        }
-
-        ans_vec
-    }
-}
diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution2.cpp b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.cpp
index 0d3f7865cf7a8..6a5746b95cd79 100644
--- a/solution/0200-0299/0239.Sliding Window Maximum/Solution2.cpp	
+++ b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.cpp	
@@ -4,17 +4,17 @@ class Solution {
         deque q;
         vector ans;
         for (int i = 0; i < nums.size(); ++i) {
-            if (!q.empty() && i - k + 1 > q.front()) {
+            if (q.size() && i - q.front() >= k) {
                 q.pop_front();
             }
-            while (!q.empty() && nums[q.back()] <= nums[i]) {
+            while (q.size() && nums[q.back()] <= nums[i]) {
                 q.pop_back();
             }
             q.push_back(i);
             if (i >= k - 1) {
-                ans.emplace_back(nums[q.front()]);
+                ans.push_back(nums[q.front()]);
             }
         }
         return ans;
     }
-};
\ No newline at end of file
+};
diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution2.go b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.go
index cd8b8d3991bbc..bc292337826f2 100644
--- a/solution/0200-0299/0239.Sliding Window Maximum/Solution2.go	
+++ b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.go	
@@ -1,10 +1,10 @@
 func maxSlidingWindow(nums []int, k int) (ans []int) {
 	q := []int{}
-	for i, v := range nums {
-		if len(q) > 0 && i-k+1 > q[0] {
+	for i, x := range nums {
+		if len(q) > 0 && i-q[0] >= k {
 			q = q[1:]
 		}
-		for len(q) > 0 && nums[q[len(q)-1]] <= v {
+		for len(q) > 0 && nums[q[len(q)-1]] <= x {
 			q = q[:len(q)-1]
 		}
 		q = append(q, i)
@@ -12,5 +12,5 @@ func maxSlidingWindow(nums []int, k int) (ans []int) {
 			ans = append(ans, nums[q[0]])
 		}
 	}
-	return ans
-}
\ No newline at end of file
+	return
+}
diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution2.java b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.java
index 7ffd8cb0ccbb3..51d0a8af9c591 100644
--- a/solution/0200-0299/0239.Sliding Window Maximum/Solution2.java	
+++ b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.java	
@@ -3,18 +3,18 @@ public int[] maxSlidingWindow(int[] nums, int k) {
         int n = nums.length;
         int[] ans = new int[n - k + 1];
         Deque q = new ArrayDeque<>();
-        for (int i = 0, j = 0; i < n; ++i) {
-            if (!q.isEmpty() && i - k + 1 > q.peekFirst()) {
+        for (int i = 0; i < n; ++i) {
+            if (!q.isEmpty() && i - q.peekFirst() >= k) {
                 q.pollFirst();
             }
             while (!q.isEmpty() && nums[q.peekLast()] <= nums[i]) {
                 q.pollLast();
             }
-            q.offer(i);
+            q.offerLast(i);
             if (i >= k - 1) {
-                ans[j++] = nums[q.peekFirst()];
+                ans[i - k + 1] = nums[q.peekFirst()];
             }
         }
         return ans;
     }
-}
\ No newline at end of file
+}
diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution2.js b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.js
new file mode 100644
index 0000000000000..767afdd61f126
--- /dev/null
+++ b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.js	
@@ -0,0 +1,22 @@
+/**
+ * @param {number[]} nums
+ * @param {number} k
+ * @return {number[]}
+ */
+var maxSlidingWindow = function (nums, k) {
+    const ans = [];
+    const q = new Deque();
+    for (let i = 0; i < nums.length; ++i) {
+        if (!q.isEmpty() && i - q.front() >= k) {
+            q.popFront();
+        }
+        while (!q.isEmpty() && nums[q.back()] <= nums[i]) {
+            q.popBack();
+        }
+        q.pushBack(i);
+        if (i >= k - 1) {
+            ans.push(nums[q.front()]);
+        }
+    }
+    return ans;
+};
diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution2.py b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.py
index a56c12edce31f..174e9085859e7 100644
--- a/solution/0200-0299/0239.Sliding Window Maximum/Solution2.py	
+++ b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.py	
@@ -2,10 +2,10 @@ class Solution:
     def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
         q = deque()
         ans = []
-        for i, v in enumerate(nums):
-            if q and i - k + 1 > q[0]:
+        for i, x in enumerate(nums):
+            if q and i - q[0] >= k:
                 q.popleft()
-            while q and nums[q[-1]] <= v:
+            while q and nums[q[-1]] <= x:
                 q.pop()
             q.append(i)
             if i >= k - 1:
diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution2.rs b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.rs
new file mode 100644
index 0000000000000..5f58a3785c28a
--- /dev/null
+++ b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.rs	
@@ -0,0 +1,29 @@
+use std::collections::VecDeque;
+
+impl Solution {
+    pub fn max_sliding_window(nums: Vec, k: i32) -> Vec {
+        let k = k as usize;
+        let mut ans = Vec::new();
+        let mut q: VecDeque = VecDeque::new();
+
+        for i in 0..nums.len() {
+            if let Some(&front) = q.front() {
+                if i >= front + k {
+                    q.pop_front();
+                }
+            }
+            while let Some(&back) = q.back() {
+                if nums[back] <= nums[i] {
+                    q.pop_back();
+                } else {
+                    break;
+                }
+            }
+            q.push_back(i);
+            if i >= k - 1 {
+                ans.push(nums[*q.front().unwrap()]);
+            }
+        }
+        ans
+    }
+}
diff --git a/solution/0200-0299/0239.Sliding Window Maximum/Solution2.ts b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.ts
new file mode 100644
index 0000000000000..9fd5cffebd083
--- /dev/null
+++ b/solution/0200-0299/0239.Sliding Window Maximum/Solution2.ts	
@@ -0,0 +1,17 @@
+function maxSlidingWindow(nums: number[], k: number): number[] {
+    const ans: number[] = [];
+    const q = new Deque();
+    for (let i = 0; i < nums.length; ++i) {
+        if (!q.isEmpty() && i - q.front()! >= k) {
+            q.popFront();
+        }
+        while (!q.isEmpty() && nums[q.back()!] <= nums[i]) {
+            q.popBack();
+        }
+        q.pushBack(i);
+        if (i >= k - 1) {
+            ans.push(nums[q.front()!]);
+        }
+    }
+    return ans;
+}