题解 | #滑动窗口的最大值#

滑动窗口的最大值

http://www.nowcoder.com/questionTerminal/1624bc35a45c42c0bc17d17fa0cba788

这个题直接用滑动窗口每次找出窗口中的最大值是非常不理想的,必须做一些优化,我做的优化就是记住上次窗口的最大值和最大值所在的下表,下个窗口再决定要不要进行所有值比较大小。

import java.util.*;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size) {
        ArrayList<Integer> list = new ArrayList<>();
        if(size>num.length||num.length==0||size==0){
            return list;
        }
        int max = Integer.MIN_VALUE;
        int maxIndex = 0;
        for(int i = 0;i<size;i++){
            if(num[i]>max){
                max = num[i];
                maxIndex = i;
            }
        }
        list.add(max);
        int lastMax = max;
        int lastMaxIndex = maxIndex;
        for(int i = 1;i<num.length-size+1;i++){
            if(num[i+size-1]>=lastMax){
                list.add(num[i+size-1]);
                lastMaxIndex = i+size-1;
                lastMax = num[i+size-1];
            }else if(num[i+size-1]<lastMax&&lastMaxIndex>=i){
                list.add(lastMax);
            }else{//只有这个情况下才对窗口内所有值进行比较,否则可直接返回最大值
                int tempMax = Integer.MIN_VALUE;
                int tempIndex = Integer.MIN_VALUE;
                for(int j = i;j<i+size;j++){
                    if(num[j]>tempMax){
                        tempMax=num[j];
                        tempIndex = j;
                    }
                }
                list.add(tempMax);
                lastMax = tempMax;
                lastMaxIndex = tempIndex;
            }
        }
        return list;
    }
}
全部评论

相关推荐

notbeentak...:孩子,说实话,选择很重要,可能你换一个方向会好很多,但是现在时间不太够了,除非准备春招
点赞 评论 收藏
分享
面了100年面试不知...:头像换成柯南再试试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务