问题描述
我正在努力处理此代码。程序意外终止。请帮忙 问题链接:https://www.hackerrank.com/challenges/maximum-element/problem
10
1 97
2
1 20
2
1 26
1 20
2
3
1 91
如果我们在程序中输入上述数字...没有到最后但在中途停止执行 请帮助我找到问题...动态分配或任何功能是否有问题...如果您有时间,请访问问题链接并寻求帮助。.谢谢
class stack
{
public:
int top = -1;
int *s;
};
void create(stack *st,int n)
{
st->s = new int[n];
}
void del(stack *st)
{
st->top--;
}
void push(stack *st,int x)
{
st->top++;
st->s[st->top] = x;
}
int main()
{
long int t;
stack st;
int choice;
int number;
int max =-1;
cin>>t;
create(&st,t);
while(t--)
{
cin>>choice;
if(choice == 1)
{
cin>>number;
push(&st,number);
if(max < number)
max = number;
}
else if(choice == 2)
{
del(&st);
}
else
{
return max;
}
}
return 0;
}
解决方法
如果使用C ++容器和算法,则可以用更短,更简洁的代码解决上述问题。
Here是一些不言自明的代码:
#include <algorithm>
#include <iostream>
#include <vector>
// driver function
int main() {
// fast I/O
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
int n,i = 0,q;
std::cin >> n;
// make a vector of n elements,here I have took size n because we have
// total n queries and in worst case all of them can be of type 1,which
// makes the maximum possible size to n
std::vector<int> v(n);
// iterate n times to read all queries
while (n--) {
// input query type
std::cin >> q;
// query type 1
if (q == 1)
// increment the top index (i) and insert value to top
std::cin >> v[++i];
// query type 2
else if (q == 2)
// decrement top,logically it is similar to removing top element
// if we always consider vector from zeroth to top index
--i;
// query type 3
else if (q == 3)
// here I am using max_element function from standard algorithms
// library
std::cout << *std::max_element(v.begin(),v.begin() + i + 1)
<< '\n';
}
}
编辑: This implementation具有较低的复杂性,无需快速的I / O就可以工作。 v2 here.检查discussion section以获得更好的(O(1)
时间复杂度)实现。