算法 --- 剑桥offer之滑动窗口的最大值

题目描述:

给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}。

Java源码实现:

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
        ArrayList<Integer> resultList = new ArrayList<>();
        int index = 0;
        if (num.length == 0 || size < 0) return null;
        if (size == 0) return resultList;
        if (num.length < size) return resultList;
        for (int i = 0; i < num.length - size + 1;i++) {
            index = i;
            for (int j = i; j - i < size;j++) {
                if (num[index] < num[j]) {
                    index = j;
                }
            }
            resultList.add(num[index]);
        }
        return resultList;
    }
}
发布了42 篇原创文章 · 获赞 3 · 访问量 3907

猜你喜欢

转载自blog.csdn.net/zhangting19921121/article/details/104488218