2024/9/5 Hot100 substring
This commit is contained in:
parent
1f2a50782b
commit
8ba279f371
|
@ -0,0 +1,41 @@
|
||||||
|
package com.cool.hot100.substring;
|
||||||
|
|
||||||
|
import java.util.Deque;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Created with IntelliJ IDEA.
|
||||||
|
*
|
||||||
|
* @Author: Cool
|
||||||
|
* @Date: 2024/09/05/13:46
|
||||||
|
* DayNumber 2
|
||||||
|
* Hard 3
|
||||||
|
* Level ?
|
||||||
|
*/
|
||||||
|
public class Num239 {
|
||||||
|
|
||||||
|
|
||||||
|
public int[] maxSlidingWindow(int[] nums, int k) {
|
||||||
|
int[] ans = new int[nums.length - k + 1];
|
||||||
|
Deque<Integer> queue = new LinkedList<>();
|
||||||
|
for (int i = 0; i < k; i++) {
|
||||||
|
while (!queue.isEmpty() && nums[queue.peekLast()] <= nums[i]) {
|
||||||
|
queue.pollLast();
|
||||||
|
}
|
||||||
|
queue.offerLast(i);
|
||||||
|
}
|
||||||
|
ans[0] = nums[queue.peekFirst()];
|
||||||
|
for (int i = k; i < nums.length; i++) {
|
||||||
|
while (!queue.isEmpty() && nums[queue.peekLast()] <= nums[i]) {
|
||||||
|
queue.pollLast();
|
||||||
|
}
|
||||||
|
queue.offerLast(i);
|
||||||
|
while (!queue.isEmpty() && i - queue.peekFirst() >= k) {
|
||||||
|
queue.pollFirst();
|
||||||
|
}
|
||||||
|
ans[i - k + 1] = nums[queue.peekFirst()];
|
||||||
|
}
|
||||||
|
return ans;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue