2363. 合并相似的物品

class Solution {
    struct my_cmp{
         bool operator()(const vector<int> &ite1, const vector<int> &ite2) {
            return ite1[0] < ite2[0]; // 升序
        }
    } cmp;
public:
    vector<vector<int>> mergeSimilarItems(vector<vector<int>>& items1, vector<vector<int>>& items2) {
        sort(items1.begin(), items1.end(), cmp);
        sort(items2.begin(), items2.end(), cmp);
        vector<vector<int>> ret;
        int i1 = 0, i2 = 0;
        while( i1 < items1.size() && i2 < items2.size()) {
            if(items1[i1][0] == items2[i2][0]) {
                ret.push_back({items1[i1][0], items1[i1][1] + items2[i2][1]});
                ++i1;
                ++i2;
            }
            else if(items1[i1][0] < items2[i2][0]) {
                ret.push_back(items1[i1]);
                ++i1;
            }
            else {
                ret.push_back(items2[i2]);
                ++i2;
            }
        } 
        while(i1 < items1.size()) {
                ret.push_back(items1[i1]);
                ++i1;
        }
        while(i2 < items2.size()) {
                ret.push_back(items2[i2]);
                ++i2;
        }
        return ret;
    }
};
posted @ 2023-02-28 15:11  小超不挑食  阅读(16)  评论(0编辑  收藏  举报