滑动窗口的最大值
来源:互联网 发布:微信如何发淘宝优惠券 编辑:程序博客网 时间:2024/05/18 00:48
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、代码:
public static void main(String[] args){ ArrayList<Integer> res = new MaxInWindows().maxInWindows(new int[]{16,14,12,10,8,6,4}, 5); for (Iterator iterator = res.iterator(); iterator.hasNext();) { Integer integer = (Integer) iterator.next(); System.out.println(integer); } } public ArrayList<Integer> maxInWindows(int [] num, int size) { ArrayList<Integer> res = new ArrayList<Integer>(); int len = num.length; if(num == null || len == 0 || size == 0 || size > len) return res; Map<String, Integer> map = getMax(num, 0, size - 1); res.add(map.get("first_value")); System.out.println(map.get("first_index")+" "+map.get("first_value")); for(int i = size; i < len ; i++){ if(num[i] >= map.get("first_value")){ res.add(num[i]); map.put("first_index", i); map.put("first_value", num[i]); }else { if(num[i-size] != map.get("first_value")){//最大值不是将要滑走的元素,即第一个元素 res.add(map.get("first_value")); }else{ map = getMax(num, i - size + 1, i); res.add(map.get("first_value")); } } System.out.println(map.get("first_index")+" "+map.get("first_value")); } return res; } //获得最大值 private Map<String,Integer> getMax(int[] num, int start, int end){ Map<String,Integer> map = new HashMap<String, Integer>(); int i, first_value = num[start], first_index = 0; //获得最大值 for(i = start; i <= end; i++){ if(num[i] > first_value){ first_index = i; first_value = num[i]; } } map.put("first_index", first_index); map.put("first_value", first_value); return map; }
阅读全文
0 0
- 滑动窗口的最大值
- 滑动窗口的最大值
- 滑动窗口的最大值
- 滑动窗口的最大值
- 滑动窗口的最大值
- 滑动窗口的最大值
- 滑动窗口的最大值
- 滑动窗口的最大值
- 滑动窗口的最大值
- 滑动窗口的最大值
- 滑动窗口的最大值
- 滑动窗口的最大值
- 滑动窗口的最大值
- 滑动窗口的最大值
- 滑动窗口的最大值
- 滑动窗口的最大值
- 滑动窗口的最大值
- 滑动窗口的最大值
- 01背包
- Spring Boot配置多个DataSource
- WebView.destroy()报错called while still attached
- 一个成功的分析团队:角色与职责
- 6-1 顺序表操作集
- 滑动窗口的最大值
- C语言实现字符串切片
- h5 的一些方法及属性
- Hadoop环境搭建
- Android onCreate等多次被执行的问题
- JavaScript 扫雷
- BP神经网络以及在手写数字分类中python代码的详细注释
- python学习
- Javascript面向对象编程(二):构造函数的继承