1. 程式人生 > 其它 >480. Sliding Window Median(Leetcode每日一題-2021.02.03)--抄答案

480. Sliding Window Median(Leetcode每日一題-2021.02.03)--抄答案

技術標籤:leetcode每日一題202102leetcode滑動視窗leetcode堆

Problem

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.

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.

Example

Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
在這裡插入圖片描述
Therefore, return the median sliding window as [1,-1,-1,3,5,6].

Solution

class Solution {
public:
    int k;
    multiset<int> left, right;

    double get_medium() {
        if (k % 2) return *right.begin();
        return ((double)*left.rbegin() + *right.begin()) / 2;
    }

    vector<double> medianSlidingWindow(vector<int>& nums, int _k) {
        k =
_k; for (int i = 0; i < k; i ++ ) right.insert(nums[i]); for (int i = 0; i < k / 2; i ++ ) { left.insert(*right.begin()); right.erase(right.begin()); } vector<double> res; res.push_back(get_medium()); for (int i = k; i < nums.size(); i ++ ) { int x = nums[i], y = nums[i - k]; if (x >= *right.begin()) right.insert(x); else left.insert(x); if (y >= *right.begin()) right.erase(right.find(y)); else left.erase(left.find(y)); while (left.size() > right.size()) { right.insert(*left.rbegin()); left.erase(left.find(*left.rbegin())); } while (right.size() > left.size() + 1) { left.insert(*right.begin()); right.erase(right.begin()); } res.push_back(get_medium()); } return res; } };