zoukankan      html  css  js  c++  java
  • 【Leetcode】239. Sliding Window Maximum

    问题描述:

    For example,
    Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

    Window position                Max
    ---------------               -----
    [1  3  -1] -3  5  3  6  7       3
     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       5
     1  3  -1  -3 [5  3  6] 7       6
     1  3  -1  -3  5 [3  6  7]      7
    

    Therefore, return the max sliding window as [3,3,5,5,6,7].、

    问题分析:

      又是一道区间最值的题,又要求近线性时间的复杂度。我首先想到用set来维护k区间个元素。

    问题解决:

      因为有重复元素,所以用multiset解决。erase的时候,因为只删除一个元素,所以用了lower_bound 当然,使用erase : find(del_val)也是可以的。重载了操作符(),从大到小排序。查了《STL源码剖析》,红黑树确实屌屌的。有时间细研下( -= ! 不知道,到毕业之前会实现这个吹过的牛逼不?)。

    最后代码:

    class Solution {
    public:
    
        struct myComp{
            bool operator () (const int &a, const int &b)
            {
                return a > b;
            }
        };
    
        vector<int> maxSlidingWindow(vector<int>& nums, int k) {
            vector<int>ret;
            for(int i = 0; i < k; i ++){
                kNums.insert(nums[i]);
            }ret.push_back(*(kNums.begin()));
            for(int i = k; i < nums.size(); i ++){
                kNums.erase(kNums.lower_bound(nums[i - k])) ;
                kNums.insert(nums[i]);
                ret.push_back(*(kNums.begin()));
            }
            for(int i = 0; i < ret.size() ; i ++)
                cout<<ret[i]<<endl;
            return ret;
        }
        multiset<int, myComp>kNums;
    };
  • 相关阅读:
    求多边形的面积
    Sequence operation3397
    Atlantis1542(线段树求矩形覆盖面积)
    hdu3033 分组背包(每组最少选一个)
    poj3468A Simple Problem with Integers(线段树延时更新)
    Picture 1828
    Minimum Inversion Number 1394(线段树法)
    hdu2955 Robberies 01背包
    C# 对MongoDB数据库进行增删该
    C#连接MongoDB数据库应用实战
  • 原文地址:https://www.cnblogs.com/luntai/p/5404833.html
Copyright © 2011-2022 走看看