合并两个有序的数列

回顾

1
n=10 => 1+2+3+...+10

算法 1

1
2
3
4
5
6
7
public int sum(int n) {
int sum = 0;
for (int i = 0; i <= n; i++) {
sum += i;
}
return sum;
}

算法 2

1
2
3
public int sum(int n) {
return n * (n + 1) / 2;
}

Merge two sorted lists

1
2
3
a=[1,3,5,7,9]
b=[2,4,6,8]
ans=[1,2,3,4,5,6,7,8,9]

算法 1

1
2
3
4
5
6
7
public int[] merge(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
Arrays.sort(c);
return c;
}

时间复杂度 O(n*log n)

算法 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public int[] merge(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
int i = 0, j = 0, la = a.length, lb = b.length;
int p = 0;
while (i < la && j < lb) {
if (a[i] < b[j]) {
c[p++] = a[i];
i++;
} else {
c[p++] = b[j];
j++;
}
}
while (i < la) {
c[p++] = a[i];
i++;
}
while (j < lb) {
c[p++] = b[j];
j++;
}
return c;
}

时间复杂度 O(n)