算法之買帽子(求第三便宜的帽子價格)

原題

度度熊想去商場買一頂帽子,商場裏有N頂帽子,有些帽子的價格可能相同。
度度熊想買一頂價格第三便宜的帽子,問第三便宜的帽子價格是多少?

輸入描述

首先輸入一個正整數N(N <= 50),接下來輸入N個數表示每頂帽子的價格(價格均是正整數,且小於等於1000)

輸出描述

如果存在第三便宜的帽子,請輸出這個價格是多少,否則輸出-1

測試用例

10
10 10 10 10 20 20 30 30 40 40

輸出結果

30

題解

解題思想

採用最大堆的思想,用數組模擬一個元素個數爲3的最大堆並賦初始值(初始值須大於題中要求的臨界值),堆頂元素(即數組的第一個元素)永遠保持爲堆中最大,每插入一個元素,首先判斷是否跟堆中元素相同,再判斷是否比堆頂元素小,若無重複且小於堆頂元素,用其將堆頂元素覆蓋,再調用堆調整算法。循環結束後,若數組第一個元素仍爲初始值,則輸出-1,反之輸出數組第一個元素。該時間複雜度爲O(N)。類似問題有:top k問題

代碼
#include <stdio.h>

void compare(int result[]){
    if(result[1]>result[0]){
        result[1]=result[1]^result[0];
        result[0]=result[1]^result[0];
        result[1]=result[1]^result[0];
    }
    if(result[2]>result[0]){
        result[2]=result[2]^result[0];
        result[0]=result[2]^result[0];
        result[2]=result[2]^result[0];
    }
}
int main(){
    int N;
    int price;
    int result[3]={1001,1001,1001};
    int i;
    scanf("%d",&N);
    for(i=0;i<N;i++){
        scanf("%d",&price);
        if(price!=result[0]&&price!=result[1]&&price!=result[2]&&price<result[0]){
            result[0]=price;
            compare(result);
        }
    }
    if(result[0]==1001){
        result[0]=-1;
    }
    printf("%d",result[0]);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章