【发布时间】:2021-08-05 07:48:52
【问题描述】:
谁能帮我找出这段代码的错误?这是一个hackerrank问题MAXIMUM ELEMENT。对于案例 2,“maxes.pop()”行一直给我分段错误。注释掉该行实际上可以编译代码。
问题:
您有一个空序列,您将收到查询。每个查询都是以下三种类型之一:
1 x - 将元素 x 推入堆栈。
2 - 删除堆栈顶部的元素。
3 - 打印堆栈中的最大元素。
功能说明
在下面的编辑器中完成getMax函数。
getMax 有以下参数:
- 字符串操作[n]:字符串操作
返回
- int[]:每个类型 3 查询的答案
输入格式
输入的第一行包含一个整数, 。接下来的每一行都包含一个上面提到的查询。
约束
约束
所有查询均有效。
示例输入
STDIN Function
----- --------
10 operations[] size n = 10
1 97 operations = ['1 97', '2', '1 20', ....]
2
1 20
2
1 26
1 20
2
3
1 91
3
样本输出
26
91
vector<int> getMax(vector<string> operations) {
stack<int> nums;
stack<int> maxes;
vector<int> maxnums;
int max = INT_MIN;
//int top = -1;
for(long unsigned int i=0; i<operations.size(); i++){
switch(operations[i][0]){
case('1'):
cout<<"Operation 1"<<endl;
nums.push(stoi(operations[i].substr(2)));
if(nums.top() > max){
max = nums.top();
maxes.push(max);
}
break;
case('2'):
cout<<"Operation 2"<<endl;
if(max==nums.top()){
//cout<<"top element in maxes"<<maxes.top()<<endl;
maxes.pop();
max = maxes.top();
}
nums.pop();
break;
case('3'):
cout<<"Operation 3"<<endl;
maxnums.push_back(maxes.top());
break;
}
}
return maxnums;
}
【问题讨论】:
标签: c++ data-structures stack