友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

480. Sliding Window Median

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. Examples:

[2,3,4] , the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Your job is to output the median array for each window in the original array.

For example,

Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

Window position                Median
---------------               -----
[1  3  -1] -3  5  3  6  7       1
 1 [3  -1  -3] 5  3  6  7       -1
 1  3 [-1  -3  5] 3  6  7       -1
 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]      6

Therefore, return the median sliding window as [1,-1,-1,3,5,6].

*Note: *

You may assume k is always valid, ie: k is always smaller than input array’s size for non-empty array.

Answers within 10^-5 of the actual value will be accepted as correct.

思路分析

  • 一刷

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
 * 答案是正确的,超大数组测试时,超时了。
 *
 * @author D瓜哥 · https://www.diguage.com
 * @since 2024-08-30 11:45:50
 */
public double[] medianSlidingWindow(int[] nums, int k) {
  // 如果窗口是奇数,则 topSmall 多一个
  Queue<Integer> topSmall = new PriorityQueue<>((a, b) -> Integer.compare(a, b));
  // 使用 Integer.compare,防止两个最小负数相减时溢出
  Queue<Integer> topLarge = new PriorityQueue<>((a, b) -> Integer.compare(b, a));
  double[] result = new double[nums.length - k + 1];
  for (int i = 0; i < k; i++) {
    topSmall.add(nums[i]);
  }
  for (int i = 0; i < k / 2; i++) {
    topLarge.add(topSmall.poll());
  }
  // 先相处再相加,防止溢出
  result[0] = k % 2 == 1 ? 1.0 * topSmall.peek()
    : topSmall.peek() / 2.0 + topLarge.peek() / 2.0;
  for (int i = k; i < nums.length; i++) {
    int num = nums[i];
    if (topSmall.peek() <= num) {
      topSmall.add(num);
    } else {
      topLarge.add(num);
    }

    int delNum = nums[i - k];
    if (topSmall.peek() <= delNum) {
      topSmall.remove(delNum);
    } else {
      topLarge.remove(delNum);
    }
    // 添加,删除,再平衡双堆,这样才能保证堆的平衡性
    // topSmall 应该始终大于等于 topLarge
    while (topLarge.size() > topSmall.size()) {
      topSmall.add(topLarge.poll());
    }
    // topSmall 与 topLarge 的差值不能大于 1
    while (topSmall.size() - topLarge.size() > 1) {
      topLarge.add(topSmall.poll());
    }

    result[i - k + 1] = k % 2 == 1 ? 1.0 * topSmall.peek()
      : topSmall.peek() / 2.0 + topLarge.peek() / 2.0;
  }
  return result;
}