zoukankan      html  css  js  c++  java
  • 剑指Offer——滑动窗口的最大值

    1、题目描述

      给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。

    2、代码实现

    package com.baozi.offer;
    
    import java.util.ArrayList;
    import java.util.Collections;
    
    /**
     * 给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。
     * 例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,
     * 他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个:
     * {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1},
     * {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
     *
     * @author BaoZi
     * @create 2019-07-15-10:09
     */
    public class Offer31 {
        public static void main(String[] args) {
            Offer31 offer31 = new Offer31();
            int[] array = new int[]{2, 3, 4, 2, 6, 2, 5, 1};
            ArrayList<Integer> arrayList = offer31.maxInWindows(array, 3);
            for (int i = 0; i < arrayList.size(); i++) {
                System.out.println(arrayList.get(i) + "  ");
            }
        }
    
        public ArrayList<Integer> maxInWindows(int[] num, int size) {
            ArrayList<Integer> list_temp = new ArrayList<>();
            ArrayList<Integer> list = new ArrayList<>();
            if (size <= 0 || size > num.length) {
                return list;
            }
            for (int i = 0; i < num.length - size + 1; i++) {
                for (int index = i; index < size + i; index++) {
                    list_temp.add(num[index]);
                }
                Collections.sort(list_temp);
                list.add(list_temp.get(size - 1));
                list_temp.clear();
            }
            return list;
        }
    
    }
    

      

  • 相关阅读:
    ViewState EnableViewState 禁用与使用心得
    ashx获取处理数据的简单例子
    移动标签(marquee)属性详解
    SQL Server 2008 R2 企业版/开发版/标准版(中英文下载,带序列号)
    C#,Dictionary,asp.net 字典 用法及简单操作
    .net 后台提交表单,获取返回结果
    ASP.NET : 如何将服务端的多个文件打包下载
    puppet原理及配置
    linux开机启动详细流程
    SHELL日志分析 实例一
  • 原文地址:https://www.cnblogs.com/BaoZiY/p/11187681.html
Copyright © 2011-2022 走看看