2570: Merge-Two-2D-Arrays-by-Summing-Values
Easy
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<int>> mergeArrays(vector<vector<int>>& nums1, vector<vector<int>>& nums2) {
vectorint i1 = 0;
int i2 = 0;
<vector<int>> ans;
vectorwhile (i1 < nums1.size() && i2 < nums2.size()) {
if (nums1[i1][0] == nums2[i2][0]) {
.push_back({nums1[i1][0], nums1[i1][1] + nums2[i2][1]});
ans++i1;
++i2;
} else if (nums1[i1][0] <= nums2[i2][0]) {
.push_back({nums1[i1][0], nums1[i1][1]});
ans++i1;
} else {
.push_back({nums2[i2][0], nums2[i2][1]});
ans++i2;
}
}
while (i1 < nums1.size()) {
.push_back({nums1[i1][0], nums1[i1][1]});
ans++i1;
}
while (i2 < nums2.size()) {
.push_back({nums2[i2][0], nums2[i2][1]});
ans++i2;
}
return ans;
}
};