zoukankan      html  css  js  c++  java
  • Lc239_滑动窗口最大值

    //给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。 
    //
    //
    // 返回滑动窗口中的最大值。 
    //
    // 
    //
    // 进阶: 
    //
    // 你能在线性时间复杂度内解决此题吗? 
    //
    // 
    //
    // 示例: 
    //
    // 输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
    //输出: [3,3,5,5,6,7] 
    //解释: 
    //
    //  滑动窗口的位置                最大值
    //---------------               -----
    //[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 
    //
    // 
    //
    // 提示: 
    //
    // 
    // 1 <= nums.length <= 10^5 
    // -10^4 <= nums[i] <= 10^4 
    // 1 <= k <= nums.length 
    // 
    // Related Topics 堆 Sliding Window
    
    package leetcode.editor.cn;
    
    //Java:滑动窗口最大值
    public class P239SlidingWindowMaximum {
        public static void main(String[] args) {
            Solution solution = new P239SlidingWindowMaximum().new Solution();
            // TO TEST
            int[] nums = {1, 3, -1, -3, 5, 3, 6, 7};
            int k = 3;
            int[] res = solution.maxSlidingWindow(nums, k);
            for (int i = 0; i < res.length; i++) {
                System.out.println(res[i]);
            }
        }
    
        //leetcode submit region begin(Prohibit modification and deletion)
        class Solution {
            public int[] maxSlidingWindow(int[] nums, int k) {
                if (k == 0) {
                    return null;
                }
                int[] res = new int[nums.length - k + 1];
                int resIndex = 0;
                for (int i = 0,count = 0; count <= nums.length-k; i++,count++) {
                    res[resIndex++] = maxValue(nums, i, k);
                }
    
                return res;
            }
    
            int maxValue(int[] nums, int start, int len) {
                int max = nums[start];
                for (int i = start; i < len+start; i++) {
                    max = max < nums[i] ? nums[i] : max;
                }
                return max;
            }
        }
    //leetcode submit region end(Prohibit modification and deletion)
    
    }
    
  • 相关阅读:
    oc调用rest api
    EF Attach时已存在的处理方式
    设置XtraForm标题居中
    读取DBF文件数据
    GP 环境参数名称列表
    MapWinGIS.ocx 注册
    ArcEngine :The XY domain on the spatial reference is not set or invalid错误
    批量修改sql server 2008的架构
    net不安装Oracle11g客户端直接使用ODAC
    Ninject使用介绍
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/13331243.html
Copyright © 2011-2022 走看看