Quickly realize the maximum value of the window (js code)

1. What can you learn?

①Two methods of js array built-in ②The specific idea of ​​generating the window maximum value array

Look at the code first (violent solution)

//暴力求解 时间复杂度:O(n*w)
function largestWindow(arr,w){
    
    
    let arr1 = []
    for (let i = 0; i < arr.length-w+1; i++) {
    
     
        let max = arr[i]
        for(j=1;j<w;j++){
    
    
            max = max>arr[i+j]?max:arr[i+j]
        }
        arr1.push(max)  
    }
    return arr1
}

Simple code

//利用双端队列实现窗口的最大值更新 时间复杂度:0(n)
function largestWindowa(arr,w){
    
    
let arr1 = []//用来存储窗体的下标
let arr2=[]//用作记录每次窗体的最大值
for (let i = 0; i < arr.length; i++) {
    
    
    if(arr1[0]<(i+1-w)){
    
    
        arr1.shift()
    }
    while(true){
    
    
        if(arr1.length==0){
    
    
            arr1.unshift(i)
            break
        }
        let j =arr1[arr1.length-1]
        if(i==0)break
        if(arr[j]>arr[i]){
    
    
        arr1.push(i)
        break
        }else {
    
    
            arr1.pop();
        }
    }
    if(i>=w-1){
    
    
        arr2.push(arr[arr1[0]])
    }
}
return arr2
}

Specific ideas

  • If the length of the array is n and the window size is w, then a total of n-w + 1 window maximum can be generated
  • arr1 is regarded as a queue, which stores the subscript of arr, which has a head and a tail, and has rules for dequeue and enqueue
  • Dequeue rules: ①When the value of arr corresponding to the subscript stored in the tail of the arr1 team is less than or equal to the current arr[i], the tail of the arr1 team departs, and then compares again. ②When the subscript of the head of the team expires (arr1[0 ]<(i+1-w))
  • Entrance rules: ①When arr1 is empty ②When the value of arr corresponding to the subscript stored at the end of the arr1 team is greater than the current arr[i], the subscript i of arr[i] is added to the end of the team

Code download address

If you want to understand more clearly, you can give a simple example yourself, or debug the code printing process

thank

If you feel helpful to your study work, please share it with those who need it, or like and encourage it, thank you for
your support. You can add a favorite, and I will continue to update it. . .

Guess you like

Origin blog.csdn.net/XINpxXIN/article/details/104643294