leetcode-第十二周

来源:互联网 发布:stc15单片机实战指南 编辑:程序博客网 时间:2024/06/06 02:16

331. Verify Preorder Serialization of a Binary Tree

class Solution {private:    vector<string> getT(string preorder) {        vector<string> ret;        preorder += ",";        for (int i = 0; i < preorder.size(); i++) {            string tmp;            int j = i;            for (; j < preorder.size() && preorder[j] != ','; j++) tmp.push_back(preorder[j]);            i = j;            ret.push_back(tmp);        }        return ret;    }    bool dfs(const vector<string> &T, int &pos, int depth) {        if (pos >= T.size()) return false;        if (T[pos] == "#") return true;        bool ret = true;        ret &= dfs(T, ++pos, depth + 1);        ret &= dfs(T, ++pos, depth + 1);        return ret;    }public:    bool isValidSerialization(string preorder) {        vector<string> T = getT(preorder);        int pos = 0;        dfs(T, pos, 0);        cout << pos << " " << T.size() << endl;        return pos == T.size() - 1;    }};

330. Patching Array

/** * 这是贪心算法的一个应用。举个例子,对于数组 [1, 2, 3, 8] : * 1. 用一个miss来表示当前缺失的数,初始时为1,num[0] = 1,它的覆盖范围为 [1, 1] ,可以补足miss = 1 */class Solution {private:    typedef long long LL;public:    int minPatches(vector<int>& nums, int n) {        int ret = 0;        for (LL i = 0, miss = 1; miss <= n; ) {            if (i < nums.size() && nums[i] <= miss) miss += nums[i++];            else miss += miss, ret++;        }        return ret;    }};
0 0
原创粉丝点击