【发布时间】:2016-11-12 01:29:40
【问题描述】:
在尝试从HackerRank 解决此问题时,我编写了以下代码,它通过了 22/27 测试用例。不幸的是,我无法访问失败的测试用例。
问题
您有一个空序列,您将收到 N 个查询。每个查询都是以下三种类型之一:
1 x => 将元素 x 压入堆栈。
2 => 删除堆栈顶部的元素。
3 => 打印堆栈中的最大元素。
输入格式
输入的第一行包含一个整数 N。接下来的 N 行每行都包含一个上述查询。 (保证每个查询都是有效的)
约束1 <= N <= 10^51 <= x <= 10^91 <= type <= 3
输出格式
对于每个类型 3 查询,在新行上打印堆栈中的最大元素。
示例输入
10
1 97
2
1 20
2
1 26
1 20
2
3
1 91
3
样本输出
26
91
我解决这个问题的方法是 -
- 使用一个向量来保存堆栈的状态
- 使用另一个向量来保存输入的最大值
我的解决方案如下 -
#include <iostream>
#include <vector>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
vector<int> myvect; /* Vector to hold the inputs */
vector<int> mymax; /* Vector to hold max elements */
unsigned times;
unsigned type;
unsigned x;
cin >> times;
if (times <= 100000) {
for (unsigned i = 0; i < times; i++) {
cin >> type;
if (type >= 1 && type <= 3) {
switch (type) {
case 1:
cin >> x;
if (x <= 1000000000) {
myvect.push_back(x);
if (mymax.empty())
mymax.push_back(x);
else if (x > mymax.back())
mymax.push_back(x);
}
break;
case 2:
if (!myvect.empty()) {
if (!mymax.empty() && (myvect.back() == mymax.back()))
mymax.pop_back();
myvect.pop_back();
}
break;
case 3:
cout << mymax.back() << endl;
break;
default:
cout << "We should not get in here" << endl;
}
}
}
}
return 0;
}
谁能帮我找出我的代码中遗漏的错误或极端情况,以便我修复它并通过所有测试用例?
【问题讨论】:
-
您可以通过保持“运行”最大值来加快速度。使用包含推送的最大值的变量。输入命令 3 后,打印变量。当从堆栈中删除时,您可能必须确定最大值。
-
您的解决方案也很有效!这与我最初的方法非常相似,只是每次输入
option 3时我都调用find_max(),这导致某些测试用例的HackerRank 平台超时。但是,在合并了您建议的优化之后(保持“运行”最大值并仅在我们从堆栈中弹出时调用find_max()),结果完美。谢谢。
标签: c++ algorithm vector stack