Leetcode 每日一题和每日一题的下一题刷题笔记 30/30

182 阅读2分钟

Leetcode 每日一题和每日一题的下一题刷题笔记 30/30

写在前面

这是我参与更文挑战的第30天,活动详情查看:更文挑战

快要毕业了,才发现自己被面试里的算法题吊起来锤。没办法只能以零基础的身份和同窗们共同加入了力扣刷题大军。我的同学们都非常厉害,他们平时只是谦虚,口头上说着自己不会,而我是真的不会。。。乘掘金鼓励新人每天写博客,我也凑个热闹,记录一下每天刷的前两道题,这两道题我精做。我打算每天刷五道题,其他的题目嘛,也只能强行背套路了,就不发在博客里了。

本人真的只是一个菜鸡,解题思路什么的就不要从我这里参考了,编码习惯也需要改进,各位如果想找刷题高手请教问题我觉得去找 宫水三叶的刷题日记 这位大佬比较好。我在把题目做出来之前尽量不去看题解,以免和大佬的内容撞车。

另外我也希望有得闲的大佬提供一些更高明的解题思路给我,欢迎讨论哈!

好了废话不多说开始第三十天的前两道题吧!

2021.6.30 每日一题

剑指 Offer 37. 序列化二叉树

这道题。。。其实有个取巧的做法


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
private:
    TreeNode* root = new TreeNode();
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        if (root == nullptr) {
            return "null";
        }
        return to_string(root->val) + ' ' + serialize(root->left) + ' ' + serialize(root->right);
    }

    TreeNode* dfs_deserialize(istringstream &iss){
        string val;
        iss >> val;
        if(val == "null") return nullptr;
        return new TreeNode(stoi(val), dfs_deserialize(iss), dfs_deserialize(iss));
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream iss(data);
        return dfs_deserialize(iss);
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

image.png

image.png

2021.6.30 每日一题下面的题

1647. 字符频次唯一的最小删除次数

直接上代码


class Solution {
public:
    int minDeletions(string s) {
        int cnt[26];
        memset(cnt, 0, sizeof(cnt));
        for (char c : s)
        {
            ++cnt[c-'a'];
        }

        // 从大到小排序
        sort(cnt, cnt+26, greater<int>());

        int res = 0;
        // 优先降低数量小的数字
        for (int i = 1; i < 26; ++i)
        {
            if (cnt[i] > 0 && cnt[i] >= cnt[i-1])
            {
                // 计算正好不相等的情况,即比它大的值减1
                int target = cnt[i-1] - 1 >= 0 ? cnt[i-1] -1 : 0;
                res += cnt[i] - target;
                cnt[i] = target;
            }
        }

        return res;
    }
};

image.png

小结

怎么钻 OJ 的空子

参考链接