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:
nums1[i1][0] == nums2[i2][0], then:
- we know both
nums1[i1][0]andnums2[i1][0]are the elements with the smallest id out of all remaining elements- we can add the id
nums1[i1][0]as well as the sum of both values,nums1[i1][1] + nums2[i2][1]to theansarray- finally, increment both
i1andi2nums1[i1][0] < nums2[i2][0], then:
- we know
nums1[i1][0]has the smallest id out of all remaining elements- therefore, we can add the id
nums1[i1][0]and its corresponding value,nums1[i1][1]to theansarray- finally, increment
i1nums1[i1][0] > nums2[i2][0], then:
- we know
nums2[i2][0]has the smallest id out of all remaining elements- therefore, we can add the id
nums2[i2][0]and its corresponding value,nums2[i2][1]to theansarray- finally, increment
i2
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;
}
};
complexity
- Time:
O(n)- Space:
O(n)