算法題-每日氣溫

每日氣溫

根據每日氣溫列表,請從新生成一個列表,對應位置的輸入是你須要再等待多久,溫度纔會升高超過該日的天數。若是以後都不會升高,請在該位置0來代替。例如,給定一個列表temperatures=[73,74,75,71,69,72,76,73],你的輸出應該是[1,1,4,2,1,1,0,0]。提示:氣溫列表長度的範圍是[1,30000]。每一個氣溫的值的均爲華氏度,都是在[30,100]範圍內的整數。

已知條件解析

  1. 數值進進出出,要有兩個值的比較,一般用棧思想解決
  2. 試試用棧來解決
  • 73入棧,棧頂元素爲73,74與棧頂73比較,知足條件 73出棧
  • 74入棧,棧頂元素爲74,75與棧頂74比較,知足條件 74出棧
  • 75入棧,棧頂元素爲75,71與棧頂75比較,不知足
  • 71入棧,棧頂元素爲71,69與棧頂71比較,不知足
  • 69入棧,棧頂元素爲69,72與棧頂69比較,知足條件 69出棧
  • 棧頂元素71,72與棧頂71比較,知足條件 71出棧
  • 棧頂元素75,72與75比較,不知足,
  • 72入棧...
  • ...

思路

  1. 使用順序棧的方式-由於題目給的條件數組個數很少,用順序結構要比鏈式結構簡單
  2. struct結點元素能夠增長index成員變量,用來記錄在數組中的位置
  3. 輸出結果能夠是數組,能夠初始化爲0

代碼

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 8

typedef int Status;
typedef int ElemType;

typedef struct Node{
    ElemType elem;
    int index;//位置
}Node, *NodePtr;

typedef struct stack{
    Node data[MAXSIZE];
    int top;
}Stack;

Status initSqStack(Stack *S) {
    S->top = -1;
    return OK;
}

Status push(Stack *S, Node e) {
    S->data[S->top + 1] = e;
    S->top++;
    return OK;
}

Status pop(Stack *S, Node *e) {
    *e = S->data[S->top];
    S->top --;
    return OK;
}

void getTemperaturesUpperDays(int *arr, int *ret) {
    //初始化 棧
    Stack st;
    initSqStack(&st);
    
    int i = 0;
    //用數組的第0個元素 建立一個結點
    Node top;
    top.elem = arr[i];
    top.index = i;
    //入棧
    push(&st, top);
    
    //遍歷後面的數組元素
    for (i = 1; i < sizeof(arr); i++) {
        //(當前for循環的數組元素 > 棧頂元素) && 棧中有元素
        while (arr[i] > top.elem && st.top != -1) {
            //出棧
            Node temp;
            pop(&st, &temp);
            //以出棧元素中index變量爲返回數組中的位置,算i與index的差值
            ret[temp.index] = i - temp.index;
            //獲取top結點
            top = st.data[st.top];
        }
        
        //將當前的數組結點入棧
        top.elem = arr[i];
        top.index = i;
        push(&st, top);
    }
}

int main(int argc, const char * argv[]) {
    // insert code here...
    printf("Hello, World!\n");
    
    int temperatures[8] = {73,74,75,71,69,72,76,73};
    int ret[8]= {0,0,0,0,0,0,0,0};
    getTemperaturesUpperDays(temperatures, ret);
    for (int i = 0; i < 8; i++) {
        printf("%d ", ret[i]);
    }
    printf("\n");
    
    return 0;
}
複製代碼

運行

傳送門

算法題-字符串編碼算法

相關文章
相關標籤/搜索