双指针法合并顺序表

题目:

有2个顺序表table1和table2,合并成一个新的顺序表

解法1

思路:

  1. 双指针方法

复杂度:

  • 时间复杂度:
  • 空间复杂度:

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
std::vector<int> test::solution(std::vector<int> &table1, std::vector<int> &table2)
{
std::vector<int> result;
int slow = 0,fast = 0;
while (slow<table1.size()&&fast<table2.size())
{
if (table1[slow]<table2[fast])
{
result.push_back(table1[slow]);
slow++;
}
else
{
result.push_back(table2[fast]);
fast++;
}
}
while (slow<table1.size())
{
result.push_back(table1[slow]);
slow++;
}
while (fast<table2.size())
{
result.push_back(table2[fast]);
fast++;
}

return result;
}