Skip to content

Commit 99fa095

Browse files
committed
solution S239, S703
1 parent 5c77ee7 commit 99fa095

File tree

2 files changed

+98
-0
lines changed

2 files changed

+98
-0
lines changed

src/main/java/S239.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import java.util.Arrays;
2+
import java.util.LinkedList;
3+
4+
/**
5+
* LC#239:Sliding Window Maximum 滑动窗口最大值
6+
* Link:https://leetcode-cn.com/problems/sliding-window-maximum/
7+
* Solution:双端队列
8+
* @author Phoenix on 2021/8/8.
9+
*/
10+
public class S239 {
11+
12+
public int[] maxSlidingWindow(int[] nums, int k) {
13+
// 长度太短没必要执行代码
14+
if(nums == null || nums.length < 2) return nums;
15+
LinkedList<Integer> queue = new LinkedList<>();
16+
// 算出结果集长度
17+
int[] result = new int[nums.length - k + 1];
18+
// 遍历 nums 数组
19+
for (int i = 0; i < nums.length; i++) {
20+
// 如果元素比较小,直接弹出
21+
while (!queue.isEmpty() && nums[queue.peekLast()] <= nums[i]) {
22+
queue.pollLast();
23+
}
24+
// 添加下标
25+
queue.addLast(i);
26+
// 判断队列首部是否有效
27+
if(queue.peek() <= i-k) {
28+
queue.poll();
29+
}
30+
// 当长度为 k 时,保存当前窗口最大值
31+
if(i+1 >= k) {
32+
result[i+1-k] = nums[queue.peek()];
33+
}
34+
}
35+
return result;
36+
}
37+
38+
public static void main(String[] args) {
39+
int[] nums = {1,3,-1,-3,5,3,6,7};
40+
int k = 3;
41+
int[] ints = new S239().maxSlidingWindow(nums, k);
42+
System.out.println("output:" + Arrays.toString(ints));
43+
}
44+
}

src/main/java/S703.java

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import java.util.PriorityQueue;
2+
3+
/**
4+
* LC#703:数据流中的第 K 大元素
5+
* Link:https://leetcode-cn.com/problems/kth-largest-element-in-a-stream/
6+
* Solution:维护一个 MinHeap,保证堆的 size = K,堆顶为 K 元素,如果比 K 小则无法进入堆,如果比 K 大则自动淘汰最小元素,时间复杂度 O(1)
7+
* @author Phoenix on 2021/8/8.
8+
*/
9+
public class S703 {
10+
11+
// 直接使用 Java PriorityQueue(默认小顶堆)
12+
final PriorityQueue<Integer> q;
13+
final int k;
14+
15+
public S703(int k, int[] a) {
16+
this.k = k;
17+
q = new PriorityQueue<>(k);
18+
// 加入堆顶
19+
for (int n : a) {
20+
add(n);
21+
}
22+
}
23+
24+
public int add(int n) {
25+
if (q.size() < k) {
26+
q.offer(n);
27+
}else if (q.peek() < n) {
28+
q.poll();
29+
q.offer(n);
30+
}
31+
return q.peek();
32+
}
33+
34+
@Override
35+
public String toString() {
36+
return "S703{" +
37+
"q=" + q +
38+
", k=" + k +
39+
'}';
40+
}
41+
42+
public static void main(String[] args) {
43+
int[] a = {4, 5, 8, 2};
44+
S703 s = new S703(3, a);
45+
s.add(3);
46+
s.add(5);
47+
s.add(10);
48+
s.add(9);
49+
s.add(4);
50+
51+
System.out.println(s);
52+
}
53+
54+
}

0 commit comments

Comments
 (0)