一些代码记录

发布于 2024-08-19  1255 次阅读


一些代码记录

#include <iostream>
#include <sys/types.h>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<string> strs(n);
    for(int i=0;i<n;i++){
        cin >> strs[i];
    }
    sort(strs.begin(), strs.end());
    for(int i=0;i<n;i++){
        cout << strs[i] << " ";
    }
    cout << endl;
}
#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;

vector<string> split(const string& s, char delimiter) {
    vector<string> tokens;
    string token;
    stringstream ss(s);

    while (getline(ss, token, delimiter)) {
        tokens.push_back(token);
    }

    return tokens;
}

int main() {
    vector<string> strs;
    string temp;
    while (cin >> temp) {
        strs = split(temp,',');
        sort(strs.begin(),strs.end());
        for(int i=0;i<strs.size();i++){
            cout << strs[i];
            if(i!=strs.size()-1){
                cout << ",";
            }
        }
        cout << endl;
        strs.clear();
    }
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        unordered_map<int, int> rightmostValueAtDepth;
        int max_depth = -1;

        stack<pair<TreeNode*,int>> nodeStack;
        nodeStack.push({root,0});

        while (!nodeStack.empty()) {
            TreeNode* node = nodeStack.top().first;
            int depth = nodeStack.top().second;
            nodeStack.pop();

            if (node != NULL) {
                // 维护二叉树的最大深度
                max_depth = max(max_depth, depth);

                // 如果不存在对应深度的节点我们才插入
                if (rightmostValueAtDepth.find(depth) == rightmostValueAtDepth.end()) {
                    rightmostValueAtDepth[depth] =  node -> val;
                }

                nodeStack.push({node -> left,depth+1});
                nodeStack.push({node -> right,depth+1});
            }
        }

        vector<int> rightView;
        for (int depth = 0; depth <= max_depth; ++depth) {
            rightView.push_back(rightmostValueAtDepth[depth]);
        }

        return rightView;
    }
};
  • alipay_img
  • wechat_img
我是小明,喜欢数学和编程
最后更新于 2024-08-19