oj 合并有序序列
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?合并有序序列
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Time Limit: 1000/1000MS (C++/Others)?Memory Limit: 65536/65536KB (C++/Others)
Problem Description
有兩個已排序好的序列A(長度為n1),B(長度為n2),將它們合并為一個有序的序列C(長度為n=n1+n2)。0 < n1,n2 < 1000。
Input
輸入有多組測試數據,每組占兩行,第一行為A序列(均為正整數),最后為-1,表示結束。第二行為B序列(均為正整數),最后為-1,表示結束。
Output
輸出合并后的序列C,每組占一行。
Sample Input
1 3 8 9 11 -1 2 5 7 10 13 -1Sample Output
1 2 3 5 7 8 9 10 11 13解法:
思路1:使用歸并排序的思想,將兩個有序數組合并成一個有序數組,時間復雜度o(n),空間復雜度o(n)
思路2:插入排序,將其中一個數組作為基準,然后遍歷該基準數組,將另一個數組的每個元素插入到基準數組的正確位置。最后的到一個有序數組;時間復雜度o(n2),空間復雜度o(1)
我這里采用的思路1,歸并排序的思想。
C語言源碼:
#include<stdio.h> #define max 1001 int c[3002]; int* merge(int a[],int t,int b[],int v){ //歸并排序int i=0,j=0,k=0;while(i<t&&j<v){if(a[i]<b[j]){c[k++]=a[i];i++;}else{c[k++]=b[j];j++;}}while(i<t){c[k++]=a[i];i++;}while(j<v){c[k++]=b[j];j++;}return c; }int main(){int a[max];int b[max];int *c;int temp,temp1,i=0,j=0,m,n;while(scanf("%d",&temp)!=EOF){ //多組輸入while(temp!=-1){a[i++]=temp;scanf("%d",&temp);m=i;}temp1=temp; //去掉-1scanf("%d",&temp); while(temp!=-1){b[j++]=temp;scanf("%d",&temp);n=j;}temp1=temp;c=merge(a,m,b,n);for(int k=0;k<m+n;k++){printf("%d",c[k]);if(k<m+n-1)printf(" ");}printf("\n");i=0;j=0;}return 0;}?
總結
- 上一篇: 感知机的详解
- 下一篇: short,int,long ,long