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.

Idea 1: BruteForce, keep the window sorted, if it's even numbers in the window, median = nums[(k-1)/2]/2.0 + nums[k/2]/2.0 to avoid overflow, median = nums[k/2] = nums[(k-1)/2] if k is odd, hence the formula is suitable for both even or odd k.
median = nums[(k-1)/2]/2.0 + nums[k/2]/2.0
 
Time complexity: O(nk), it takes O(k) to remove outside window element and add new element while keeping window sorted
Space complexity: O(k)
 class Solution {
public double[] medianSlidingWindow(int[] nums, int k) {
if(k > nums.length) {
return new double[0];
} double[] result = new double[nums.length - k + 1]; int[] buffer = Arrays.copyOf(nums, k);
Arrays.sort(buffer);
result[0] = buffer[(k-1)/2]/2.0 + buffer[k/2]/2.0; for(int right = k; right < nums.length; ++right) {
int pos = Arrays.binarySearch(buffer, nums[right-k]);
while(pos > 0 && buffer[pos-1] > nums[right]) {
buffer[pos] = buffer[pos-1];
--pos;
} while(pos + 1 < k && buffer[pos+1] < nums[right]) {
buffer[pos] = buffer[pos+1];
++pos;
} buffer[pos] = nums[right];
result[right - k + 1] = buffer[(k-1)/2]/2.0 + buffer[k/2]/2.0;
}
return result;
}
}

python:

 class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
window = sorted(nums[0:k]) medianIndex = k
result = []
result.append(window[(k-1)//2]/2.0 + window[k//2]/2.0) for right in range(k, len(nums)):
window.remove(nums[right-k])
bisect.insort(window, nums[right])
result.append(window[(k-1)//2]/2.0 + window[k//2]/2.0) return result

Idea 2. a. Similar to find median from Data Stream LT295, besides we need to add element to the window, we need to remove element outside of window, the removing action in priority queue in java takes O(n), unless we make customized heap-based priority queue, the alternative choice is TreeSet, to deal with duplicates, use the index for equal elements.

Time complexity: O(nlogk)

Space complexity: O(k)

 class Solution {
public double[] medianSlidingWindow(int[] nums, int k) {
if(k > nums.length) {
return new double[0];
} double[] result = new double[nums.length - k + 1]; Comparator<Integer> cmp = (a, b) -> {
if(nums[a] == nums[b]) {
return a-b;
}
return Integer.compare(nums[a], nums[b]);
};
TreeSet<Integer> maxHeap = new TreeSet<>(cmp);
TreeSet<Integer> minHeap = new TreeSet<>(cmp); for(int right = 0; right < nums.length; ++right) {
maxHeap.add(right);
minHeap.add(maxHeap.pollLast()); if(maxHeap.size() < minHeap.size()) {
maxHeap.add(minHeap.pollFirst());
} if(right >= k-1) {
if(k%2 == 1) {
result[right-k+1] = nums[maxHeap.last()];
}
else {
result[right-k+1] = nums[maxHeap.last()]/2.0 + nums[minHeap.first()]/2.0;
} if(!maxHeap.remove(right-k+1)) {
minHeap.remove(right-k+1);
}
}
} return result;
}
}

Idea 2.b priority queue

Time complexity: O(nk)

Space complexity: O(k)

 class Solution {
public double[] medianSlidingWindow(int[] nums, int k) {
if(k > nums.length) {
return new double[0];
} double[] result = new double[nums.length - k + 1]; PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
PriorityQueue<Integer> minHeap = new PriorityQueue<>(); for(int right = 0; right < nums.length; ++right) {
maxHeap.add(nums[right]);
minHeap.add(maxHeap.poll()); if(maxHeap.size() < minHeap.size()) {
maxHeap.add(minHeap.poll());
} if(right >= k-1) {
if(k%2 == 1) {
result[right-k+1] = maxHeap.peek();
}
else {
result[right-k+1] = maxHeap.peek()/2.0 + minHeap.peek()/2.0;
} if(!maxHeap.remove(nums[right-k+1])) {
minHeap.remove(nums[right-k+1]);
}
}
} return result;
}
}

Idea 2.c. priority queue + hashmap to store elements outside of window, instead of remove elemnts immediately

Time complexity: O(nlogk)

Space complexity: O(n)

 class Solution {
public double[] medianSlidingWindow(int[] nums, int k) {
if(k > nums.length) {
return new double[0];
} double[] result = new double[nums.length - k + 1]; int leftCnt = 0;
int rightCnt = 0;
Map<Integer, Integer> record = new HashMap<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
PriorityQueue<Integer> minHeap = new PriorityQueue<>(); for(int right = 0; right < nums.length; ++right) {
maxHeap.add(nums[right]);
minHeap.add(maxHeap.poll()); if(maxHeap.size() -leftCnt < minHeap.size() - rightCnt) {
maxHeap.add(minHeap.poll());
} if(right >= k-1) {
if(k%2 == 1) {
result[right-k+1] = maxHeap.peek();
}
else {
result[right-k+1] = maxHeap.peek()/2.0 + minHeap.peek()/2.0;
} if(maxHeap.peek() >= nums[right-k+1]) {
if(maxHeap.peek() == nums[right-k+1]) {
maxHeap.poll();
}
else {
record.put(nums[right-k+1], record.getOrDefault(nums[right-k+1], 0) + 1);
++leftCnt;
}
}
else {
if(minHeap.peek() == nums[right-k+1]) {
minHeap.poll();
}
else {
++rightCnt;
record.put(nums[right-k+1], record.getOrDefault(nums[right-k+1], 0) + 1);
}
} while(record.containsKey(maxHeap.peek())) {
int key = maxHeap.poll();
record.put(key, record.get(key)-1);
if(record.get(key) == 0) {
record.remove(key);
}
--leftCnt;
} while(record.containsKey(minHeap.peek())) {
int key = minHeap.poll();
record.put(key, record.get(key)-1);
if(record.get(key) == 0) {
record.remove(key);
}
--rightCnt;
}
}
} return result;
}
}

最新文章

  1. SOUI开发者论坛
  2. python之路1(初识python)
  3. HackerRank &quot;Flatland Space Stations&quot;
  4. SQL语句-批量插入表(表数据插表)
  5. MSCRM 修改 默认组织
  6. Python学习基础教程(learning Python)--2.2.1 Python下的变量解析
  7. 【JS】&lt;select&gt;标签小结
  8. DataGridView单元格合并
  9. xml格式化
  10. Android中关于List与Json转化问题
  11. Unix/Linux环境C编程入门教程(25) C/C++字符测试那些事儿
  12. 微信JS-API封装接口——node.js版
  13. JavaScript开发中常用的代码规范配置文件
  14. 题解-Codeforces917D Stranger Trees
  15. Visual Studio(VS)秘钥集合
  16. day16匿名函数
  17. JavaScript 之 预编译 作用域,作用域链
  18. Day033--Python--进程
  19. Sybase&#183;调用存储过程并返回结果
  20. 小Z的袜子(hose)

热门文章

  1. Json Web Token JJWT
  2. aspectj ----- 简介
  3. Spring的一些资源
  4. nagios维护之添加监控
  5. LibreOJ 6277. 数列分块入门 1
  6. 前端、数据库、Django简单的练习
  7. HDU-1212.BigNumber(有关模数的定理)
  8. &lt;asp:Button点击查询后,调用js中函数展现加载圈
  9. ES6之扩展运算符
  10. AngularJS——第1章 简介