1475. 商品折扣后的最终价格

代码实现(自解)
class Solution {
public:
vector<int> finalPrices(vector<int>& prices) {
for (int i = 0; i < prices.size(); i++) {
for (int j = i + 1; j < prices.size(); j++) {
if (prices[j] <= prices[i]) {
prices[i] -= prices[j];
break;
}
}
}
return prices;
}
};
236. 二叉树的最近公共祖先

代码实现(自解)
class Solution {
private:
bool isFather(TreeNode* p, TreeNode* q) {
if (!p) return false;
if (p == q) return true;
return isFather(p->left, q) || isFather(p->right, q);
}
TreeNode* father(TreeNode* root, TreeNode* p) {
if (!root) return nullptr;
if (root->left == p || root->right == p) return root;
if (root->left) {
TreeNode* tmp = father(root->left, p);
if (tmp) return tmp;
}
return father(root->right, p);
}
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (p == root) return p;
if (q == root) return q;
if (isFather(p, q)) return p;
if (isFather(q, p)) return q;
return lowestCommonAncestor(root, father(root, p), father(root, q));
}
};
297. 二叉树的序列化与反序列化

代码实现(自解)
class Codec {
public:
string serialize(TreeNode* root) {
if (!root) return "";
if (root->val == 1 && !root->left && root->right) {
int i = 2;
TreeNode* tmp = root->right;
while (tmp && tmp->val == i++ && !tmp->left) tmp = tmp->right;
if (i > 100) return "*";
}
string ans = "";
map<long long, int> token;
queue<pair<long long, TreeNode*>> myQueue;
myQueue.push({1, root});
while (!myQueue.empty()) {
int sz = myQueue.size();
while (sz--) {
auto pa = myQueue.front();
myQueue.pop();
token[pa.first] = pa.second->val;
if (pa.second->left) {
myQueue.push({pa.first * 2, pa.second->left});
}
if (pa.second->right) {
myQueue.push({pa.first * 2 + 1, pa.second->right});
}
}
}
for (auto it = token.begin(); it != token.end(); it++) {
if (ans == "") {
ans += to_string(it->first) + "," + to_string(it->second);
continue;
}
ans += " " + to_string(it->first) + "," + to_string(it->second);
}
return ans;
}
TreeNode* deserialize(string data) {
if (data == "") return nullptr;
if (data == "*") {
TreeNode* root = new TreeNode(1);
TreeNode* tmp = root;
for (int i = 2; i <= 1000; i++) {
tmp->right = new TreeNode(i);
tmp = tmp->right;
}
return root;
}
map<long long, TreeNode*> token;
int pdata = 0;
int n = data.size();
while (pdata < n) {
int pnext = pdata + 1;
while (data[pnext] != ',') pnext++;
long long t1 = stoi(data.substr(pdata, pnext - pdata));
pnext += 2;
pdata = pnext - 1;
while (pnext != n && data[pnext] != ' ') pnext++;
int t2 = stoi(data.substr(pdata, pnext - pdata));
token[t1] = new TreeNode(t2);
pdata = pnext + 1;
if (t1 == 1) continue;
if (t1 % 2 == 0) {
token[t1 / 2]->left = token[t1];
}
else {
token[t1 / 2]->right = token[t1];
}
}
return token[1];
}
};