leetcode 栈

92 篇文章 0 订阅
72 篇文章 0 订阅

接雨水

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

在这里插入图片描述

#include <iostream>
#include <vector>

using namespace std;

int trap(vector<int> &height)
{
    int lmax=0, rmax=0;
    int length = height.size();
    int left = 0, right = length - 1;
    vector<int> rain(length, 0);

    while(left<right)
    {
        lmax = max(height[left], lmax);
        rmax = max(height[right], rmax);

        if(lmax <= rmax)
        {
            rain[left] = lmax - height[left];
            left++;
        }
        else
        {
            rain[right] = rmax - height[right];
            right--;
        }
    }
    int count=0;
    for(int i=0; i<length; i++)
        count += rain[i];

    return count;
}

int main()
{
    vector<int>height = {0,1,0,2,1,0,1,3, 2, 1, 2, 1};
    cout<<trap(height)<<endl;
    return 0;
}

简化路径

以 Unix 风格给出一个文件的绝对路径,你需要简化它。或者换句话说,将其转换为规范路径。
在 Unix 风格的文件系统中,一个点(.)表示当前目录本身;此外,两个点 (…) 表示将目录切换到上一级(指向父目录);两者都可以是复杂相对路径的组成部分。更多信息请参阅:Linux / Unix中的绝对路径 vs 相对路径
请注意,返回的规范路径必须始终以斜杠 / 开头,并且两个目录名之间必须只有一个斜杠 /。最后一个目录名(如果存在)不能以 / 结尾。此外,规范路径必须是表示绝对路径的最短字符串。

string simplifyPath(string path)
{
    if(path.size() == 0) return "";
    vector<string> elems;
    int p=0, q=1;
    int l = path.length();
    while(q!=l)
    {
        if(path[q] != '/')
        {
            q++;
        }
        else
        {
            if(q-p == 1)
            {
                p = q;
                q++;
                continue;
                
            }
            else if(path[p]!= '/')
                elems.push_back(path.substr(p, q-p));
            else
                elems.push_back(path.substr(p+1, q-p-1));
            
            p = q;
            q ++;
        }
    }
    if(p!=q && p != q-1) elems.push_back(path.substr(p+1, q-p-1));
    
    string res = "";
    int i = elems.size()-1;
    int drop_num = 0;
    while(i>=0)
    {
        if(elems[i] == ".")
        {
            i--;
        }
        else if(elems[i] == "..")
        {
            i--;
            drop_num ++;
        }
        else if(drop_num != 0)
        {
            i = i-1;
            drop_num--;
        }
        else
        {
            res = "/" + elems[i] + res;
            i--;
        }
    }
    if(res.length()==0) res = "/";
    return res;

}

执行用时 : 24 ms, 在Simplify Path的C++提交中击败了10.26% 的用户
内存消耗 : 13.2 MB, 在Simplify Path的C++提交中击败了0.52% 的用户

柱状图中最大的矩形

给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。

int largestRectangleArea(vector<int> &heights) {
    int MaxArea = 0;
    
    stack<int>S;
    heights.push_back(0);
    for(int i=0; i<heights.size(); i++)
    {
        if(S.empty() || heights[i]>= heights[S.top()])
        {
            S.push(i);
        }
        else
        {
            int index = S.top();
            S.pop();
            int Area = 0;
            if(S.empty()) Area = heights[index] * i;
            else Area = heights[index] * (i-S.top()-1);
            i--;
            if(MaxArea < Area) MaxArea=Area;
        }
    }
    return MaxArea;
};

执行用时 : 20 ms, 在Largest Rectangle in Histogram的C++提交中击败了36.13% 的用户
内存消耗 : 10.7 MB, 在Largest Rectangle in Histogram的C++提交中击败了0.00% 的用户

最大矩形

给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

int maximalRectangle(vector<vector<char>>& matrix) {
    if(matrix.empty()) return 0;
    
    int MaxRectangle = 0;
    vector<int> each(matrix[0].size());
    
    for (vector<vector<char>>::iterator it = matrix.begin(); it != matrix.end(); ++it)
    {
        for (int i = 0; i < (*it).size(); ++i)
        {
            if((*it)[i] == '0')
            {
                each[i] = 0;
            }
            else
            {
                each[i] ++;
            }
            
        }
        MaxRectangle = max(MaxRectangle, largestRectangleArea(each));
        
    }
        return MaxRectangle;
}

执行用时 : 56 ms, 在Maximal Rectangle的C++提交中击败了4.55% 的用户
内存消耗 : 12 MB, 在Maximal Rectangle的C++提交中击败了0.00% 的用户

二叉树的中序遍历

/**
 * 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<int> inorderTraversal(TreeNode* root) {
        vector<int> result;
		stack<TreeNode*> myStack;//辅助栈,由于保护现场
		while (!myStack.empty() || root != NULL) {
			if (root != NULL && root->left != NULL) {//如果左子树不为空
				myStack.push(root);//保护现场
				root = root->left;//先访问左子树
				continue;
			}
			if (root == NULL) {
				if (!myStack.empty()) {
					root = myStack.top();//恢复现场
					myStack.pop();
				}
				else {
					break;
				}
			}
			result.push_back(root->val);//访问当前跟节点
			root = root->right;//访问右子树
		}
		return result;
       

    } 
};

执行用时 : 12 ms, 在Binary Tree Inorder Traversal的C++提交中击败了11.56% 的用户
内存消耗 : 9.1 MB, 在Binary Tree Inorder Traversal的C++提交中击败了0.79% 的用户

二叉树的前序遍历

/**
 * 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<int> preorderTraversal(TreeNode* root) {
        stack<TreeNode *>Node;
        vector<int>res;
        if(root == nullptr) return res;
        
        Node.push(root);
        while(!Node.empty())
        {
            TreeNode *father = Node.top();
            Node.pop();
            res.push_back(father->val);
            if(father->right != nullptr) Node.push(father->right);
            if(father->left != nullptr) Node.push(father->left);
        }
        return res;
    }
};

执行用时 : 12 ms, 在Binary Tree Preorder Traversal的C++提交中击败了11.96% 的用户
内存消耗 : 9.1 MB, 在Binary Tree Preorder Traversal的C++提交中击败了0.75% 的用户

二叉树的锯齿形层次遍历

/**
 * 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>> zigzagLevelOrder(TreeNode* root) {
        
        vector<vector<int>> res;
        
        if(root==nullptr) return res;
        queue<TreeNode *>Node;
        
        Node.push(root);
        int CurCount = 1;
        int NextCount = 0;
        int nums = 1;
        
        while(!Node.empty())
        {
            vector<int> each;
            while(CurCount >0)
            {
                TreeNode *tmp = Node.front();
                each.push_back(tmp->val);
                Node.pop();
                if(tmp->left != nullptr)
                {
                    Node.push(tmp->left);
                    NextCount ++;
                }
                if(tmp->right != nullptr)
                {
                    Node.push(tmp->right);
                    NextCount ++;
                }
                CurCount--;
            }
            if(nums%2==0)
            {
                reverse(each.begin(),each.end());
            }
            nums++;
            res.push_back(each);
            CurCount = NextCount;
            NextCount = 0;
        }
        return res;
        
    }
};

执行用时 : 20 ms, 在Binary Tree Zigzag Level Order Traversal的C++提交中击败了6.52% 的用户
内存消耗 : 13.4 MB, 在Binary Tree Zigzag Level Order Traversal的C++提交中击败了0.87% 的用户

二叉树的后序遍历

/**
 * 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<int> postorderTraversal(TreeNode* root) {
        vector<int>res;
        if(root==nullptr) return res;
        
        stack<TreeNode *> Node;
        stack<TreeNode *> RNode;
        bool hasRight = false;
        Node.push(root);
        RNode.push(Node.top());
        while(!Node.empty())
        {
                   
            if(Node.top()->right != nullptr && !hasRight)
            {
                Node.push(Node.top()->right);
                RNode.push(Node.top());
            }
            
            else
            {
                TreeNode * tmp = Node.top();
                Node.pop();
                hasRight = true;
                if(tmp->left!=nullptr) 
                {
                    Node.push(tmp->left);
                    RNode.push(Node.top());
                    hasRight = false;
                }
            }
            
            
            
        }
        while(!RNode.empty())
        {
            res.push_back(RNode.top()->val);
            RNode.pop();
        }
        return res;
            
        
    }
};

执行用时 : 12 ms, 在Binary Tree Postorder Traversal的C++提交中击败了10.91% 的用户
内存消耗 : 9 MB, 在Binary Tree Postorder Traversal的C++提交中击败了0.88% 的用户

逆波兰表达式求值

int getRes(int a, int b, int symbol)
{
    if(symbol==0) return a+b;
    if(symbol==1) return a-b;
    if(symbol==2) return a*b;
    else return a/b;
}

int evalRPN(vector<string>& tokens) {
    if(tokens.empty()) return 0;
    map<string, int> Symbol;
    Symbol["+"] = 0;
    Symbol["-"] = 1;
    Symbol["*"] = 2;
    Symbol["/"] = 3;
    
    stack<string> Comput;
    Comput.push(tokens[0]);
    int i=1, l= tokens.size();
    while(i<l)
    {
        if(Symbol.count(tokens[i])>0)
        {
            int a = atoi(Comput.top().c_str() );
            Comput.pop();
            int b = atoi(Comput.top().c_str() );
            Comput.pop();
            int c =getRes(a,b,Symbol[tokens[i]]);
            Comput.push(to_string(getRes(b,a,Symbol[tokens[i]])));
        }
        else
        {
            Comput.push(tokens[i]);
        }
        i++;
    }
    return atoi(Comput.top().c_str());
    
}

执行用时 : 32 ms, 在Evaluate Reverse Polish Notation的C++提交中击败了6.98% 的用户
内存消耗 : 12.7 MB, 在Evaluate Reverse Polish Notation的C++提交中击败了0.71% 的用户

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值