O(n + log k) C++ code


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

Log in to reply
 

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