480. Sliding Window Median¶
Difficulty: Hard
LeetCode Problem View on GitHub
480. Sliding Window Median
Hard
The 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 values.
- For examples, if
arr = [2,3,4], the median is3. - For examples, if
arr = [1,2,3,4], the median is(2 + 3) / 2 = 2.5.
You are given an integer array nums and an integer k. 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.
Return the median array for each window in the original array. Answers within 10-5 of the actual value will be accepted.
Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 Output: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000] Explanation: 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
Example 2:
Input: nums = [1,2,3,4,2,3,1,4,2], k = 3 Output: [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]
Constraints:
1 <= k <= nums.length <= 105-231 <= nums[i] <= 231 - 1
Solution¶
class Solution {
public double[] medianSlidingWindow(int[] nums, int k) {
int n = nums.length;
Comparator<Integer> comparator = new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
if(nums[a] != nums[b]) return Integer.compare(nums[a), nums[b]);
else return a - b;
}
};
TreeSet<Integer> maxSet = new TreeSet<>(comparator.reversed());
TreeSet<Integer> minSet = new TreeSet<>(comparator);
double res[] = new double[n - k + 1];
int current_idx = 0;
for (int i = 0; i < k; i++) {
maxSet.add(i);
minSet.add(maxSet.pollFirst());
if (minSet.size() > maxSet.size()) maxSet.add(minSet.pollFirst());
}
res[current_idx++] = getMedian(minSet, maxSet, nums);
int start = 0;
for (int i = k; i < n; i++) {
if (minSet.contains(start)) minSet.remove(start);
if (maxSet.contains(start)) maxSet.remove(start);
start++;
maxSet.add(i);
minSet.add(maxSet.pollFirst());
if (minSet.size() > maxSet.size()) maxSet.add(minSet.pollFirst());
res[current_idx++] = getMedian(minSet, maxSet, nums);
}
return res;
}
private double getMedian(TreeSet<Integer> minSet, TreeSet<Integer> maxSet, int nums[]) {
if (minSet.size() == maxSet.size()) {
double current_res = nums[maxSet.first()] * 1.0 + nums[minSet.first()] * 1.0;
current_res = current_res / 2 * 1.0;
return current_res;
}
return (double)(nums[maxSet.first()] * 1.0);
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here