zoukankan      html  css  js  c++  java
  • LeetCode Candy

    typedef pair<int, int> P;
    
    class Solution {
    public:
        int _candy(vector<int> &ratings) {
            int len = ratings.size();
            if (len == 0) return 0;
            
            vector<P> rate_pos;
            vector<int> candy(len, 1);
            
            rate_pos.resize(len);
            
            for (int i=0; i<len; i++) {
                rate_pos[i] = make_pair(ratings[i], i);
            }
            
            sort(rate_pos.begin(), rate_pos.end());
            
            int total = 0;
            
            for (int i=0; i<len; i++) {
                int pos = rate_pos[i].second;
                int rat = rate_pos[i].first;
                
                if (pos > 0 && ratings[pos-1] < rat && candy[pos] <= candy[pos-1]) {
                    candy[pos] = candy[pos-1] + 1;
                }
                if (pos < len-1 && ratings[pos+1] < rat && candy[pos] <= candy[pos+1]) {
                    candy[pos] = candy[pos+1] + 1;
                }
                
                total += candy[pos];
            }
            return total;
        }
        
        int candy(vector<int> &ratings) {
            int len = ratings.size();
            if (len < 2) return len;
            vector<int> candy(len, 1);
            
            for (int i=1; i<len; i++) {
                if (ratings[i] > ratings[i-1]) {
                    candy[i] = candy[i-1] + 1;
                }
            }
            
            for (int i=len-1; i>=1; i--) {
                if (ratings[i-1] > ratings[i] && candy[i-1] <= candy[i]) {
                    candy[i-1] = candy[i] + 1;
                }
            }
            int total = 0;
            for (int i=0; i<len; i++) total += candy[i];
            
            return total;
        }
    };

    如果直接找出rating的各个极值点,然后在单调区间内求出各自需要的数目(从rating低的方向向rating高的方向扫描),就不需要辅助数组了

  • 相关阅读:
    Nginx 日志切割-定时(附数据库数据备份)
    安装Nginx
    系统自适应限流
    黑名名单控制-sentinel
    热点参数的流量控制
    流量控制文档说明
    在Linux中输入命令时打错并按了enter
    配置maven环境
    项目层次展示
    寻找cmd的管理员运行
  • 原文地址:https://www.cnblogs.com/lailailai/p/3672794.html
Copyright © 2011-2022 走看看