1、用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
class Solution { public: void push(int node) { stack1.push(node); } int pop() { if(stack2.empty()){ while(!stack1.empty()){ stack2.push(stack1.top()); stack1.pop(); } } int res = stack2.top(); stack2.pop(); return res; } private: stack<int> stack1; stack<int> stack2; };2.定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数。
思路:定义两个栈,一个栈正常保存数据,一个栈的栈顶永远是当前栈中最小元素。
class Solution { public: void push(int value) { s1.push(value); if(s2.empty()){ s2.push(value); }else{ if(value > s2.top()){ s2.push(s2.top()); }else{ s2.push(value); } } } void pop() { s1.pop(); s2.pop(); } int top() { return s1.top(); } int min() { return s2.top(); } private: stack<int> s1; stack<int> s2; };3.输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
思路:
(1)建立一个辅助栈,将栈的压入序列压入到辅助栈中;
(2)压入一个元素就与弹出序列相比较,如果辅助栈顶元素与弹出序列相等就弹出;
(3)最后判断辅助栈元素是否被完全弹出,如果完全弹出了返回False,否则返回True。
class Solution { public: bool IsPopOrder(vector<int> pushV,vector<int> popV) { vector<int>::iterator iter1, iter2; iter2 = popV.begin(); stack<int> mdata; for(iter1=pushV.begin(); iter1 != pushV.end(); iter1++){ mdata.push(*iter1); while(!mdata.empty() && mdata.top() == *iter2){ mdata.pop(); iter2++; } } if(mdata.empty()) return true; else return false; } };4、给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
class Solution { public: vector<int> maxInWindows(const vector<int>& num, unsigned int size) { vector<int> res; int n = num.size(); for(int i = 0; i < n; i++){ if(size > 0 && i + size <= n){ int tmp = num[i]; for(int j = i+1; j < i+size; j++){ tmp = max(num[j], tmp); } res.push_back(tmp); } } return res; } };