问题描述
谁能帮我找出这段代码的错误?这是一个hackerrank问题最大元素。对于情况 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;
}
解决方法
考虑以下输入序列:
1 1 // push 1. Pushes 1 into nums and maxes
1 1 // push 1. Pushes 1 into nums,but not into maxes,since max = 1.
3 // delete top stack element
3 // delete top stack element
在处理第一行 3
之前,您的状态是这样的:
nums = {1,1}
maxes = {1}
max = 1
现在,在第一次弹出时,一切都会好起来的,所以在第一次弹出后,你会以这种状态结束:
nums = {1}
maxes = {}
max = 1
但是,在第二次弹出时,max == nums.top()
仍然为真,因此您从已经为空的 maxes
堆栈中弹出。这就是为什么它会给你分段错误。