Sliding Window Median LT480

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)
 1 class Solution {
 2     public double[] medianSlidingWindow(int[] nums, int k) {
 3         if(k > nums.length) {
 4             return new double[0];
 5         }
 6         
 7         double[] result = new double[nums.length - k + 1];
 8         
 9         int[] buffer = Arrays.copyOf(nums, k);
10         Arrays.sort(buffer);
11         result[0] = buffer[(k-1)/2]/2.0 + buffer[k/2]/2.0; 
12         
13         for(int right = k; right < nums.length; ++right) {
14             int pos = Arrays.binarySearch(buffer, nums[right-k]);
15             while(pos > 0 && buffer[pos-1] > nums[right]) {
16                 buffer[pos] = buffer[pos-1];
17                 --pos;
18             }
19             
20             while(pos + 1 < k && buffer[pos+1] < nums[right]) {
21                 buffer[pos] = buffer[pos+1];
22                 ++pos;
23             }
24             
25             buffer[pos] = nums[right];
26             result[right - k + 1] = buffer[(k-1)/2]/2.0 + buffer[k/2]/2.0;
27         }
28         return result;
29     }
30 }

python:

 1 class Solution:
 2     def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
 3         window = sorted(nums[0:k])
 4         
 5         medianIndex = k
 6         result = []
 7         result.append(window[(k-1)//2]/2.0 + window[k//2]/2.0)
 8         
 9         for right in range(k, len(nums)):
10             window.remove(nums[right-k])
11             bisect.insort(window, nums[right])
12             result.append(window[(k-1)//2]/2.0 + window[k//2]/2.0)
13             
14         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)

 1 class Solution {
 2     public double[] medianSlidingWindow(int[] nums, int k) {
 3         if(k > nums.length) {
 4             return new double[0];
 5         }
 6         
 7         double[] result = new double[nums.length - k + 1];
 8         
 9         Comparator<Integer> cmp = (a, b) -> {
10             if(nums[a] == nums[b]) {
11                 return a-b;
12             }
13             return Integer.compare(nums[a], nums[b]);
14         };
15         TreeSet<Integer> maxHeap = new TreeSet<>(cmp);
16         TreeSet<Integer> minHeap = new TreeSet<>(cmp);
17         
18         for(int right = 0; right < nums.length; ++right) {
19             maxHeap.add(right);
20             minHeap.add(maxHeap.pollLast());
21             
22             if(maxHeap.size() < minHeap.size()) {
23                 maxHeap.add(minHeap.pollFirst());
24             }
25             
26             if(right >= k-1) {
27                 if(k%2 == 1) {
28                     result[right-k+1] = nums[maxHeap.last()];
29                 }
30                 else {
31                     result[right-k+1] = nums[maxHeap.last()]/2.0 + nums[minHeap.first()]/2.0;
32                 }
33                 
34                 if(!maxHeap.remove(right-k+1)) {
35                     minHeap.remove(right-k+1);
36                 }
37             }
38         }
39         
40         return result;
41     }
42 }

Idea 2.b priority queue

Time complexity: O(nk)

Space complexity: O(k)

 1 class Solution {
 2     public double[] medianSlidingWindow(int[] nums, int k) {
 3         if(k > nums.length) {
 4             return new double[0];
 5         }
 6         
 7         double[] result = new double[nums.length - k + 1];
 8         
 9         
10         PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
11         PriorityQueue<Integer> minHeap = new PriorityQueue<>();
12         
13         for(int right = 0; right < nums.length; ++right) {
14             maxHeap.add(nums[right]);
15             minHeap.add(maxHeap.poll());
16             
17             if(maxHeap.size() < minHeap.size()) {
18                 maxHeap.add(minHeap.poll());
19             }
20             
21             if(right >= k-1) {
22                 if(k%2 == 1) {
23                     result[right-k+1] = maxHeap.peek();
24                 }
25                 else {
26                     result[right-k+1] = maxHeap.peek()/2.0 + minHeap.peek()/2.0;
27                 }
28                 
29                 if(!maxHeap.remove(nums[right-k+1])) {
30                     minHeap.remove(nums[right-k+1]);
31                 }
32             }
33         }
34         
35         return result;
36     }
37 }

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)

 1 class Solution {
 2     public double[] medianSlidingWindow(int[] nums, int k) {
 3         if(k > nums.length) {
 4             return new double[0];
 5         }
 6         
 7         double[] result = new double[nums.length - k + 1];
 8         
 9         int leftCnt = 0;
10         int rightCnt = 0;
11         Map<Integer, Integer> record = new HashMap<>();
12         PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
13         PriorityQueue<Integer> minHeap = new PriorityQueue<>();
14         
15         for(int right = 0; right < nums.length; ++right) {
16             maxHeap.add(nums[right]);
17             minHeap.add(maxHeap.poll());
18             
19             if(maxHeap.size() -leftCnt < minHeap.size() - rightCnt) {
20                 maxHeap.add(minHeap.poll());
21             }
22             
23             if(right >= k-1) {
24                 if(k%2 == 1) {
25                     result[right-k+1] = maxHeap.peek();
26                 }
27                 else {
28                     result[right-k+1] = maxHeap.peek()/2.0 + minHeap.peek()/2.0;
29                 }
30                 
31                 if(maxHeap.peek() >= nums[right-k+1]) {
32                     if(maxHeap.peek() == nums[right-k+1]) {
33                         maxHeap.poll();
34                     }
35                     else {
36                         record.put(nums[right-k+1], record.getOrDefault(nums[right-k+1], 0) + 1);
37                         ++leftCnt;
38                     }
39                 }
40                 else {
41                     if(minHeap.peek() == nums[right-k+1]) {
42                         minHeap.poll();
43                     }
44                     else {
45                         ++rightCnt;
46                         record.put(nums[right-k+1], record.getOrDefault(nums[right-k+1], 0) + 1);
47                     }
48                 }
49                 
50                 while(record.containsKey(maxHeap.peek())) {
51                     int key = maxHeap.poll();
52                     record.put(key, record.get(key)-1);
53                     if(record.get(key) == 0) {
54                         record.remove(key);
55                     }
56                     --leftCnt;
57                 }
58                 
59                 while(record.containsKey(minHeap.peek())) {
60                     int key = minHeap.poll();
61                     record.put(key, record.get(key)-1);
62                     if(record.get(key) == 0) {
63                         record.remove(key);
64                     }
65                     --rightCnt;
66                 }
67             }
68         }
69         
70         return result;
71     }
72 }

猜你喜欢

转载自www.cnblogs.com/taste-it-own-it-love-it/p/10591699.html