10 lines C++, O(n log k) using multiset


  • 2
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        vector<int> out;
        multiset<int> window;
        for (int i=0; i<nums.size(); i++) {
            window.insert(nums[i]);
            if (i >= k - 1) {
                out.push_back(*window.rbegin());
                window.erase(window.find(nums[i-k+1]));
            }
        }
        return out;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.