zoukankan      html  css  js  c++  java
  • 2020-7-15

    407. 接雨水 II

    题解: 维护一个小根堆,从外向内进行遍历。
    class Solution {
    public:
        struct cell{
            int x, y, h;
            bool operator < (const cell & rs)const{
                return h > rs.h;
            }
        };
        bool vis[125][125];
        int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1};
        int trapRainWater(vector<vector<int>>& heightMap) {
            int n = heightMap.size() , m = heightMap[0].size();
            priority_queue <cell> q;
            for(int i=0;i<n;i++) { q.push({i, 0 , heightMap[i][0]}); vis[i][0] = 1;}
            for(int i=0;i<n;i++) { q.push({i, m-1 , heightMap[i][m-1]}); vis[i][m-1] = 1;}
            for(int i=0;i<m;i++) { q.push({0, i , heightMap[0][i]}); vis[0][i] = 1;}
            for(int i=0;i<m;i++) { q.push({n-1, i , heightMap[n-1][i]}); vis[n-1][i] = 1;}
            
            int ans = 0;
            while(q.size()){
                cell now = q.top(); q.pop();
                for(int i=0;i<4;i++){
                    int xx = now.x + dx[i], yy = now.y+dy[i];
                    if(xx<0 || yy<0 || xx>=n || yy>=m || vis[xx][yy]) continue;
                    ans += max(now.h - heightMap[xx][yy], 0);
                    vis[xx][yy] = 1;
                    q.push({xx, yy, max(heightMap[xx][yy], now.h)});
                }
            }
            return ans;
        }
    };
    View Code

    402. 移掉K位数字

    题解: 单调栈,  若 123a456 < 123b456 那么 a<b 也就是说两个相同位数的数字大小关系取决于第一个不同的数的大小。所以我们要让前面的保留数字尽可能的小, 则我们的策略就是遍历到当前数字时,去看它前面那个数字,如果还没有删够k个并且前面的数字大于当前的数字,我们就把之前的数字删掉(这样前一位的数字就能更小)。最终保留 n-k个数字。

    class Solution {
    public:
        string removeKdigits(string num, int k) {
            stack <int> stk;
            for(int i=0;i<num.size();i++){
                while(k && stk.size() && stk.top() > num[i]) {
                    stk.pop();
                    k-=1;
                }
                stk.push(num[i]);
            }
            while(k && stk.size()){ stk.pop();k--;} 
            string ans;
            while(stk.size()) {ans += stk.top(); stk.pop();}
            if(ans.size()==0) return "0";
            reverse(ans.begin(), ans.end());
            int i=0;
            while(ans[i]=='0') i++;
            if(ans.substr(i).size()==0) return "0";
            return ans.substr(i);
        }
    };
    View Code
  • 相关阅读:
    IOS 获取时间的问题
    JQ 点赞
    截取字符串第一个空格前的字符
    JQ 的一些方法
    匿名函数var a =function(){}和function a(){}的区别
    完美支持中文编程的 Emacs 配置文件 .emacs
    linux find 命令忽略某个或多个子目录的方法
    Linux下如何用date设置时间
    nagios的监控代码!
    shell脚本监控apache进程数和oracle连接数
  • 原文地址:https://www.cnblogs.com/liyinggang/p/13347960.html
Copyright © 2011-2022 走看看