牛客编程巅峰赛S2第5场

求中位数和平均数的比较

class Solution {
public:
    /**
     *
     * @param arr int整型vector
     * @return int整型
     */
    int Answerofjudge(vector<int>& arr) {
        // write code here
        sort(arr.begin(), arr.end());
        int len = arr.size();

        double mid, avg;
        if (len % 2 == 0) {
            mid = (arr[len / 2 - 1] + arr[len/2]) / 2.0;
        }
        else {
            mid = arr[len / 2];
        }
        long long sum = 0;
        for (int n : arr) sum += n;
        avg = (double)sum / (double)len;
        if (avg == mid) return 0;
        else if (avg > mid) return -1;
        else return 1;
    }
};

双指针求满足某个条件的最大长度

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 返回符合题意的最长的子串长度
     * @param x string字符串
     * @return int整型
     */
    unordered_map<char, int> npy;
    int Maximumlength(string x) {
        // write code here
        npy['n'] = 0, npy['p'] = 0, npy['y'] = 0;
        int left = 0;
        int res = 0;
        for (int i = 0; i < x.size(); i++) {
            npy[x[i]]++;
            while (npy['n'] > 0 && npy['p'] > 0 && npy['y'] > 0) {
                npy[x[left]]--;
                left++;
            }
            res = max(res, i - left + 1);
        }
        return res;
    }
};

后缀表达式

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 给定一个后缀表达式,返回它的结果
     * @param str string字符串
     * @return long长整型
     */
    long long solve(string str) {
        // write code here
        long long temp = 0;
        stack<long long> s;
        for (int i=0; i<str.size(); i++) {
            if(str[i] <= '9' && str[i] >= '0') temp = temp * 10 + str[i] - '0';
            else if(str[i] == '#') {
                s.push(temp); temp = 0;
            } else {
                long long n1 = s.top(); s.pop();
                long long n2 = s.top(); s.pop();
                if(str[i] == '+') s.push(n1 + n2);
                else if(str[i] == '-') s.push(n2 - n1);
                else s.push(n1 * n2);
            }
        }
        return s.top();
    }
};

总结

题目非常简单的,但是第一次手写后缀表达式(还是简化版),在减号那里没有注意顺序...
说明算法看懂了还不行,必须得手写一遍,过一遍OJ,能马上写出来才算掌握