题1:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
c++
实现.
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int> s;
int t = 0;
for(int x : pushed){
s.push(x);
while(!s.empty() && popped[t] == s.top()){
s.pop();
t++;
}
}
return s.empty();
}
};
c++
优化.
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
int i = 0, j = 0;
for(int x : pushed){
pushed[i] = x;
while(i >= 0 && pushed[i] == popped[j]){
j++;
i--;
}
i++;
}
return i == 0;
}
};
作者:Sunny_SMILE
链接:https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof/solution/jian-zhi-offer-31-zhan-de-ya-ru-dan-chu-c0hiu/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
python
实现.
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
stack = []
i = 0
for x in pushed:
stack.append(x)
while stack and stack[-1] == popped[i]:
stack.pop()
i += 1
return not stack
题2:从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
若每位扣友选择不同的一题,请返回被选的 N 道题目至少包含多少种知识点类型。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/WqXACV
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
c++
实现.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
if(!root) return ans;
queue<TreeNode *> points;
points.push(root);
while(points.size()){
int col=points.size();
vector<int> ans1;
for(int i=0;i<col;i++){
TreeNode *temp=points.front();
points.pop();
ans1.push_back(temp->val);
if(temp->left) points.push(temp->left);
if(temp->right) points.push(temp->right);
}
ans.push_back(ans1);
}
return ans;
}
};
python
实现.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root: return []
res, queue = [], collections.deque()
queue.append(root)
while queue:
tmp = []
for _ in range(len(queue)):
node = queue.popleft()
tmp.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
res.append(tmp)
return res
作者:jyd
链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof/solution/mian-shi-ti-32-ii-cong-shang-dao-xia-da-yin-er-c-5/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。