2570: Merge-Two-2D-Arrays-by-Summing-Values
Easy
table of contents
I start off with 2 pointers,
i1 = 0 and i2 = 0, which are used to iterate
through nums1 and nums2 respectively.
Creating ans as our resultant array, since both
nums1 and nums2 are in ascending
order, if:
We can repeat the conditional until we reach the end of
nums1 or nums2 (or both).
Finally, to complete ans, we can just append all the
remaining elements in either nums1 or
nums2 before simply returning ans.
code
class Solution {
public:
vector<vector<int>> mergeArrays(vector<vector<int>>& nums1, vector<vector<int>>& nums2) {
int i1 = 0;
int i2 = 0;
vector<vector<int>> ans;
while (i1 < nums1.size() && i2 < nums2.size()) {
if (nums1[i1][0] == nums2[i2][0]) {
ans.push_back({nums1[i1][0], nums1[i1][1] + nums2[i2][1]});
++i1;
++i2;
} else if (nums1[i1][0] <= nums2[i2][0]) {
ans.push_back({nums1[i1][0], nums1[i1][1]});
++i1;
} else {
ans.push_back({nums2[i2][0], nums2[i2][1]});
++i2;
}
}
while (i1 < nums1.size()) {
ans.push_back({nums1[i1][0], nums1[i1][1]});
++i1;
}
while (i2 < nums2.size()) {
ans.push_back({nums2[i2][0], nums2[i2][1]});
++i2;
}
return ans;
}
};