Brush Questions-Sword refers to Offer-64. The maximum value of the sliding window (dual pointer)

64. Maximum sliding window

Topic link

Source: Jianzhi Offer
Link: https://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788?tpId=13&&tqId=11217&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

Title description

Given an array and the size of the sliding window, find the maximum value of all the sliding windows. For example, if the input array {2,3,4,2,6,2,5,1} and the sliding window size 3, then there are 6 sliding windows in total, and their maximum values ​​are {4,4,6, 6,6,5}; There are 6 sliding windows for the array {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,3,4,2,6,[2,5, 1]}.
When the window is larger than the length of the array, return empty

Example 1
Input
Copy
[2,3,4,2,6,2,5,1],3
Return value
Copy
[4,4,6,6,6,5]

Topic analysis

Note for application windows The
length of the sliding window can be fixed or variable. According to the requirements of the topic,
two pointers can be used to identify the boundary of the window.

import java.util.*;
public class Solution {
    
    
    public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
    
    
        ArrayList<Integer> list = new ArrayList<>();
        if(size<1 || num.length<size){
    
    
            return list;
        }
        //窗口长度固定
        int left = 0;
        int right = size-1;
        while(right < num.length)
        {
    
    
            list.add(calcMax(num,left,right));
            left++;
            right++;
        }
        return list;
    }
    /**计算出当前数组[left,right]范围内最大的数字*/
    public int calcMax(int[] num,int left,int right)
    {
    
    
        int max = num[left];
        for(int i = left; i<=right; i++){
    
    
            if(num[i] > max)
            {
    
    
                max = num[i];
            }
        }
        return max;
    }
}

Guess you like

Origin blog.csdn.net/qq_42771487/article/details/113359024