[InterviewBit] Merge Two Sorted Lists II

Merge Two Sorted Lists II

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void Solution::merge(vector<int> &A, vector<int> &B) {
vector<int> res;
while(A.size() and B.size()) {
auto& ma = A.back() > B.back() ? A : B;
res.push_back(ma.back());
ma.pop_back();
}
while(A.size()) {
res.push_back(A.back());
A.pop_back();
}
while(B.size()) {
res.push_back(B.back());
B.pop_back();
}
reverse(begin(res),end(res));
swap(res,A);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/26/PS/interviewbit/merge-two-sorted-lists-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.