02 线性表

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 12

线性表 (a1,a2,…,an)

• 例 1 字母表 A,B,C,…
• 例 2 中国 2000~2020 历年 GDP (万亿美元):
( 1.21 , 1.34 , 1.47 , 1.66 , 1.96 , 2.29 , 2.75 , 3.55 , 4.60 , 5.11 , 6.10 , 7.57 ,
8.56 , 9.61 , 10.48 , 11.06 , 11.19 , 12.23 , 13.89 , 14.28 , 14.72 )
• 例 3 学生登记表

姓名 学号 性别 年龄 籍贯
王 xx 2151101 男 20 河北
李 xx 2151102 女 21 广东
赵 xx 2151103 女 22 江苏
张 xx 2151104 男 20 四川
… … … … …
合并( union )
有两个线性表 La 、 Lb 。将所有在 Lb 中但不在 La 中的元素插入到 La 的末尾

01 void union(List *La,List Lb){


02 int La_len,Lb_len,i; ElemType e;
03 La_len=ListLength(La);Lb_len=ListLength(Lb);
04 for (i=1;i<=Lb_len;i++){ // nb 次
05 GetElem(Lb,i,&e); // t1
06 if(!LocateElem(La,e,equal)) Listlnsert(La,++La_len,e);
// cna+t2
07 }
08 }
设 La 和 Lb 表长分别为 na 和 nb , GetElem 和 ListInsert 所需时间为 t1 和 t2( 与表长无
关 ) , LocateElem 执行时间与表长成正比( = cna ),
则上述算法执行时间为 nb(t1+cna+t2) ,
时间复杂度为 O(nanb) 。
归并( merge ):将两个有序(递增)线性表合并成一个有序(递增)线
性表。
1 2 3 4
i
La 3 5 8 11 …

j
Lb 2 6 8 9 …

k
Lc
1 2 3 4
i
La 3 5 8 11 …

j
Lb 2 6 8 9 …

k
Lc 2
1 2 3 4
i
La 3 5 8 11 …

j
Lb 2 6 8 9 …

k
Lc 2
1 2 3 4
i
La 3 5 8 11 …

j
Lb 2 6 8 9 …

k
Lc 2 3
1 2 3 4
i
La 3 5 8 11 …

j
Lb 2 6 8 9 …

k
Lc 2 3
1 2 3 4
i
La 3 5 8 11 …

j
Lb 2 6 8 9 …

k
Lc 2 3 5
01 void MergeList(List La,List Lb,List *Lc){
02 int La_len,Lb_len,i,j,k; ElemType ai,bj;
03 InitList(Lc); i=j=1;k=0;
04 La_len=ListLength(La); Lb_len=ListLength(Lb);
05 while((i<=La_len)&&(j<=Lb_len)){
06 GetElem(La,i,&ai); GetElem(Lb,j,&bj);
07 if(ai<=bj) {ListInsert(Lc,++k,ai);++i;}
08 else {ListInsert(Lc,++k,bj);++j;}
09 } // La 遍历完或 Lb 遍历完则结束
10 while(i<=La_len){ // Lb 已经结束,遍历 La 剩下的
11 GetElem(La,i++,&ai); ListInsert(Lc,++k,ai);
12 }
13 while(j<=Lb_len){ // La 已经结束,遍历 Lb 剩下的
14 GetElem(Lb,j++,&bj); ListInsert(Lc,++k,bj);
15 }
16 } // 执行时间为 (na+nb) (t1+t2) ,时间复杂度为 O(na+nb) 。
练习 1 :在一个增序的数组里找到两个数,使它们的和为给定值。已知有且只有一对解。

例 Input: a = [2,7,11,15], target = 13 ,


Output: [1,3] 。
第一个数字 2 和第三个数字 11 的和等于给定值 13 。

vector<int> twoSum(vector<int>& a, int target) {


int l = 0, r = a.size() - 1, sum;
while (l < r) {
sum = a[l] + a[r];
if (sum == target) break;
if (sum < target) ++l;
else --r;
}
return vector<int>{l + 1, r + 1};
}
练习 2 :给出⼀个⾮负数组 a1 , …… , an ,每个整数标识⼀个竖⽴在坐标轴 x 整数位置的
⼀堵⾼度为 ai 的墙。选择两堵墙,它们与 x 轴构成的容器可以容纳最多的⽔。

例 Input: [1,8,6,2,5,4,8,3,7] , Output: 49 。

x
1 2 3 4 5 6 7 8 9
func maxArea(a []int) int { // GO 语言
max,l,r := 0,0,len(a)-1 //max 是最大面积, l 和 r 是容器左右两端
for l < r { // 相当于 while 循环
width,high := r-l,0
// 移动高墙只会使面积更小,所以移矮墙
if a[l] < a[r] {
high = a[l] // 高度由矮墙决定
l++
} else {
high = a[r]
r--
}
temp := width * high // 面积
if temp > max { max = temp }
}
return max
}

You might also like