两个序列中位数算法c语言,PAT 2-13 两个有序序列的中位数(C语言实现)

题目描述:

已知有两个等长的非降序序列S1, S2, 设计函数求S1与S2并集的中位数。有序序列A0, A1…AN-1的中位数指A(N-1)/2的值,即第[(N+1)/2]个数(A0为第1个数)。

输入格式说明:

输入分3行。第1行给出序列的公共长度N(0

输出格式说明:

在一行中输出两个输入序列的并集序列的中位数。

样例输入与输出:

序号

输入

输出

1

5

1 3 5 7 9

2 3 4 5 6

4

2

6

-100 -10 1 1 1 1

-50 0 2 3 4 5

1

3

3

1 2 3

4 5 6

3

4

3

4 5 6

1 2 3

3

5

1

2

1

1

解答说明:

利用两个序列都是非降序排列的特性,现将两个序列合并,再取第(N-1)/2个数即可。可调用前面对两个链表进行合并所写的函数。

源码:

#include

typedef struct node *ptrNode;

typedef ptrNode LinkList; //头结点

typedef ptrNode Position;//中间节点

typedef int ElementType;

struct node{

ElementType Element;

Position next;

};

LinkList creatList(int n)

{

LinkList head,r,p;

int x,i;

head = (struct node*)malloc(sizeof(struct node)); //生成新结点

r = head;

for(i = 0; i < n; i++){

scanf("%d",&x);

p = (struct node*)malloc(sizeof(struct node));

p->Element = x;

r->next = p;

r = p;

}

r->next = NULL;

return head;

}

LinkList mergeList(LinkList a, LinkList b)

{

Position ha, hb,hc;

LinkList c,r,p;

ha = a->next;

hb = b->next;

c = (struct node*)malloc(sizeof(struct node));

r = c;

while((ha != NULL)&&(hb != NULL)){

p = (struct node*)malloc(sizeof(struct node));

if(ha->Element <= hb->Element){

p->Element = ha->Element;

ha = ha->next;

}

else{

p->Element = hb->Element;

hb = hb->next;

}

r->next = p;

r = p;

}

if(ha == NULL){

while(hb != NULL){

p = (struct node*)malloc(sizeof(struct node));

p->Element = hb->Element;

hb = hb->next;

r->next = p;

r = p;

}

}

if(hb == NULL){

while(ha != NULL){

p = (struct node*)malloc(sizeof(struct node));

p->Element = ha->Element;

ha = ha->next;

r->next = p;

r = p;

}

}

r->next = NULL;

return c;

}

int medianOfLinklist(LinkList L, int n)

{

LinkList ha;

int i;

ha = L;

for(i = 0; i <= (n-1)/2;i++){

ha = ha->next;

}

return ha->Element;

}

int main(void)

{

LinkList L1,L2,L3;

int n,median;

scanf("%d",&n);

L1 = creatList(n);

L2 = creatList(n);

L3 = mergeList(L1,L2);

median = medianOfLinklist(L3, 2*n);

printf("%d",median);

return 0;

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
题目描述: 给定两个长度为n的有序序列A和B,本题要求时间复杂度为O(logn)的算法,找出两个序列中位数。 输入格式: 第一行输入一个整数n,表示序列的长度。 第二行输入n个整数,表示序列A。 第三行输入n个整数,表示序列B。 输出格式: 输出一个整数,表示两个序列中位数。 输入样例: 5 1 3 5 7 9 2 4 6 8 10 输出样例: 5 解题思路: 中位数的定义是:将一个集合分成两个长度相等的子集,其中一个子集中的元素总是大于另一个子集中的元素。根据这个定义,我们可以将两个有序序列分别划分成两个长度相等的子集,使得一个子集中的元素总是大于另一个子集中的元素。假设序列A和序列B的长度都为n,我们可以将序列A和序列B分别划分成两个长度为n/2的子序列,分别为A1、A2和B1、B2。如果A1的中位数小于B1的中位数,那么A1中的元素肯定都小于两个序列中位数,因此可以将A1中的元素全部舍去,将A2和B1、B2组成新的序列,继续进行划分。如果A1的中位数大于B1的中位数,那么B1中的元素肯定都小于两个序列中位数,因此可以将B1中的元素全部舍去,将A1、A2和B2组成新的序列,继续进行划分。如果A1的中位数等于B1的中位数,那么A1和B1中的元素都小于两个序列中位数,因此可以将A1、B1和A2、B2组成新的序列,继续进行划分。每次划分后,序列的长度都会减半,因此时间复杂度为O(logn)。 代码实现
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值