] [Prove safety offer maximum sliding window

Title Description

Given an array and the size of the sliding window, sliding window to find the maximum value among all values. For example, if the input array size and {2,3,4,2,6,2,5,1} 3 sliding window, then the presence of a total of six sliding window, their maximum values ​​is {4,4,6, 6,6,5}; it has the following six array {2,3,4,2,6,2,5,1} for the sliding window: {[2,3,4], 2,6,2,5 , 1}, {2, [3,4,2], 6,2,5,1}, {2,3, [4,2,6], 2, 5}, {2,3,4 , [2,6,2], 5,1}, {2,3,4,2, [6,2,5], 1}, {2,3,4,2,6, [2,5, 1]}.

Problem-solving ideas

  1. Brute force method, the maximum value of the index record, if the index is not within the window range, the re-election of a new index.

My code

import java.util.*;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
        ArrayList<Integer> max = new ArrayList<>();
        if(num == null || num.length == 0 || size == 0 || size > num.length) return max;
        int maxIndex = 0, i = 0;
        for(; i < size; i++){
            if(num[i] > num[maxIndex]) maxIndex = i;
        }
        max.add(num[maxIndex]);
        for(; i < num.length; i++){
            if(num[i] > num[maxIndex]) maxIndex = i;
            if(maxIndex <= i - size){
                maxIndex = i - size + 1;
                for(int j = i - size + 1; j <= i; j++){
                    if(num[j] > num[maxIndex]) maxIndex = j;
                }
            }
            max.add(num[maxIndex]);
        }
        return max;
    }
}

Published 77 original articles · won praise 1 · views 5322

Guess you like

Origin blog.csdn.net/u010659877/article/details/104097971