zoukankan      html  css  js  c++  java
  • CCI_Q3.2

    本文参考该作者文章当作编程笔记:
    
    作者:Hawstein
    出处:http://hawstein.com/posts/ctci-solutions-contents.html

    Q:

    实现一个栈,除了push和pop操作,还要实现min函数以返回栈中的最小值。 push,pop和min函数的时间复杂度都为O(1)。

    思路:

    额外建立一个保存栈中目前最小值的数组gpStacMin[],如果入栈的数据小于等于gpStacMin中的栈顶数据,同时入栈。弹出时候,只要弹出的栈顶元素和gpStacMin中的栈顶数据相等,同时弹出。

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #define N 10
     4 int *gpStac,*gpStacMin;
     5 int gCoutStac=-1,gCoutStacMin=-1;
     6 void initStack()
     7 {
     8     gpStac=(int *)malloc(sizeof(int)*N);
     9     gpStacMin=(int *)malloc(sizeof(int)*N);
    10 }
    11 void stackPush(int num)
    12 {
    13     gpStac[++gCoutStac]=num;
    14     if(gCoutStacMin==-1)
    15         gpStacMin[++gCoutStacMin]=num;
    16     else if(num<=gpStacMin[gCoutStacMin])
    17             gpStacMin[++gCoutStacMin]=num;
    18 }
    19 int stackPop()
    20 {
    21     if(gpStac[gCoutStac]==gpStacMin[gCoutStacMin])
    22         --gCoutStacMin;
    23     return gpStac[gCoutStac--];
    24 }
    25 int stackMin()
    26 {
    27     return gpStacMin[gCoutStacMin];
    28 }
    29 int main()
    30 {
    31     initStack();
    32     int i;
    33     stackPush(3);
    34     stackPush(2);
    35     stackPush(1);
    36     stackPush(4);
    37     stackPush(2);
    38     stackPush(1);
    39     stackPush(3);
    40     for(i=0;i<N-3;i++)
    41     {
    42         printf("%d	",stackMin());
    43         stackPop();
    44     }
    45     free(gpStac);
    46     free(gpStacMin);
    47     return 0;
    48 }
  • 相关阅读:
    CodeForces Round #545 Div.2
    HDU 2222 Keywords Search
    拓扑排序
    CodeForces Round #553 Div2
    CodeForces Round #552 Div.3
    CodeForces Round #549 Div.2
    #Leetcode# 997. Find the Town Judge
    Educational Codeforces Round 62
    #Leetcode# 524. Longest Word in Dictionary through Deleting
    圆方树小结
  • 原文地址:https://www.cnblogs.com/jhooon/p/3593187.html
Copyright © 2011-2022 走看看