1.14 Blog de aprendizaje

Hoy resumo una pila de preguntas medianas y difíciles
. El rectángulo más grande del histograma
Inserte la descripción de la imagen aquí
Inserte la descripción de la imagen aquí

【算法思路】单调栈
 1.构建单调增栈
 2.数据入栈,如果大于等于栈顶,则直接入栈
 3.如果小于栈顶,则结算栈顶
 4.最终数据的统计,到起始位置,要统计全长度
 (不好理解的话建议将例子代入来理解)
 部分代码如下:
int maxi(int a,int b){
    
    
    if(a<b)return b;
    else{
    
    return a;}
}
int largestRectangleArea(int* heights, int heightsSize){
    
    
    if(heightsSize == 0) {
    
    
        return 0;
    }
    //放置数据下标
    int *stk = calloc(heightsSize, sizeof(int));
    int ssize = 0;
    stk[ssize++] = 0;
    int max = 0;
    for(int i = 1; i < heightsSize; i++) {
    
    
        int top_h = heights[stk[ssize - 1]];
        if(heights[i] >= top_h) {
    
    
            stk[ssize++] = i;
            continue;
        }
        //结算栈顶数据
        while(ssize > 0) {
    
    
            top_h = heights[stk[ssize - 1]];
            if(heights[i] >= top_h) {
    
    
                break;
            }
            //从栈前一个位置算起
            int width = ssize - 1 == 0? i : i - 1 - stk[ssize - 2];
            max = maxi(max, top_h * width);
            ssize--;
        }
        //将当前数据放入栈顶,目前该数据为栈内最大
        stk[ssize++] = i;
    }
      //结算最后栈内数据
    for(int i = ssize - 1; i >= 0; i--) {
    
    
        int top_h = heights[stk[i]];
        int width = i == 0? heightsSize : heightsSize - 1 - stk[i - 1];
        max = maxi(max, top_h * width);
    }
    return max;
}

Supongo que te gusta

Origin blog.csdn.net/weixin_47529865/article/details/112637540
Recomendado
Clasificación