Skip to content

Commit 310d5fa

Browse files
authored
Create Merge Two 2D Arrays by Summing Values
1 parent f289b09 commit 310d5fa

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
想法:因為兩者都是 ascending order,所以最小者只會出現在前面,我們只需每次將最小者 pop 掉並寫到新的 array 即可
2+
如果遇到兩個頭部一樣小就合併後再寫入 array
3+
4+
// assume there is n element in nums1 , m elements in nums2
5+
Time Complexity : O(n + m) for traversing two arrays
6+
Space Complexity : O(n + m) for the output array
7+
8+
class Solution {
9+
public:
10+
vector<vector<int>> mergeArrays(vector<vector<int>>& nums1, vector<vector<int>>& nums2) {
11+
vector<vector<int>> ans ;
12+
int index1 = 0 , index2 = 0 ;
13+
while ( index1 < nums1.size() || index2 < nums2.size() ) {
14+
if ( index1 == nums1.size() ) {
15+
ans.push_back( nums2[index2++] ) ;
16+
}
17+
else if ( index2 == nums2.size() ) {
18+
ans.push_back( nums1[index1++] ) ;
19+
}
20+
else {
21+
// compare num1[index1] and nums2[index2]
22+
if ( nums1[index1][0] < nums2[index2][0] ) {
23+
ans.push_back( nums1[index1++] ) ;
24+
}
25+
else if ( nums1[index1][0] > nums2[index2][0] ) {
26+
ans.push_back( nums2[index2++] ) ;
27+
}
28+
else {
29+
ans.push_back(
30+
{nums1[index1][0] , nums1[index1][1] + nums2[index2][1]} ) ;
31+
index1++ , index2++ ;
32+
}
33+
}
34+
}
35+
return ans ;
36+
}
37+
};

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy