![](/img/trans.png)
[英]After using Dynamic Programing in the below question why i m getting time limit exceed?
[英]why am i getting time limit exceed
我試圖在 leetcode 中解決這個問題。 問題:堆問題
這是我的代碼:
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& score) {
priority_queue<pair<int,int>,vector<pair<int,int>>>mxheap;
for(int i=0; i<score.size(); i++){
mxheap.push({score[i],i});
}
vector<string>ans(score.size());
int place = 1;
while(!mxheap.empty()){
switch(place){
case 1:
ans[mxheap.top().second] = "Gold Medal";
mxheap.pop();
break;
case 2:
ans[mxheap.top().second] = "Silver Medal";
mxheap.pop();
break;
case 3:
ans[mxheap.top().second] = "Bronze Medal";
mxheap.pop();
break;
default:
ans[mxheap.top().second] = to_string(place);
}
place++;
}
return ans;
}
};
我不知道為什么我的時間限制超過了我也嘗試刪除這對並使用地圖,但這也不起作用。 我還在討論部分看到了一些答案,這些答案也具有 (nlogn) 時間復雜度,但它們運行良好,我的 (nlogn) 仍然無法正常工作,有人可以告訴我我在這里做錯了什么。
因為在default
情況下您不會彈出元素。
ans[mxheap.top().second] = to_string(place);
mxheap.pop(); // Add this
這會導致無限循環,因為您的隊列永遠不會變空,因此 TLE。
您應該使用調試器找出這些問題的根源,並在程序中添加斷點以驗證這些點處的預期程序狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.