• 【刷题-LeetCode】239. Sliding Window Maximum


    1. Sliding Window Maximum

    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. Return the max sliding window.

    Follow up:
    Could you solve it in linear time?

    Example:

    Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
    Output: [3,3,5,5,6,7] 
    Explanation: 
    
    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
    

    很奇怪很多答案为什么又是堆又是哈希表的。。。

    用一个tmp_max变量记录窗口里的最大值,向右移动时,如果最左边出去的是最大值tmp_max,就在窗口里重新线性搜索或者调用max_element()或者其他什么方法找到最大值,右端点进来的新的值和tmp_max比较一下取大的作为新的tmp_max

    class Solution {
    public:
        vector<int> maxSlidingWindow(vector<int>& nums, int k) {
            int l = 0, r = k;
            vector<int>ans;
            int tmp = INT_MIN;
            for(int i = 0; i < r; ++i)tmp = max(nums[i], tmp);
            ans.push_back(tmp);
            r++;
            l++;
            while(r <= nums.size()){
                if(tmp == nums[l-1]){
                    tmp = INT_MIN;
                    for(int i = l; i < r; ++i)tmp = max(tmp, nums[i]);
                }else{
                    tmp = max(tmp, nums[r-1]);
                }
                ans.push_back(tmp);
                l++;
                r++;
            }
            return ans;
        }
    };
    
  • 相关阅读:
    SQL Server 存储过程
    FindControl的详细介绍
    Transaction-SQL 游标
    硬盘安装工具nt6 hdd installer无法卸载的问题
    Some question about Source Tree
    java 简单加密
    java 多态与多重继承
    构造方法和方法的重载
    64位WIN7上安装11G R2 ,PLSQL的配置方法
    语录(排名不分先后)
  • 原文地址:https://www.cnblogs.com/vinnson/p/13365331.html
Copyright © 2020-2023  润新知