☆1029

找中位数

如果用两个数组会超过内存范围。只能是现存以一个然后,另一个在读取的时候,进行比较。

因为存在遍历完某个数组的情况,为了避免这种情况带来的复杂性。在数组的末端加入INF,这样就永远不用分析遍历完数组的情况。

中位数应该是  (hght + low +1)/2; 

要注意 index 和  i ,   j 指向的都是还未进行操作的元素。

代码如下:

 1 #include <cstdio>
 2 using namespace std;
 3 const int maxn=200100;
 4 const int INF=0x7fffffff;
 5 int a[maxn];
 6 int main()
 7 {
 8     int len1 ,len2;
 9     scanf("%d",&len1);
10     for(int i=0;i<len1;i++)scanf("%d",&a[i]);
11     scanf("%d",&len2);
12     a[len1]=INF;
13     int mpos=(len1+len2-1)/2;
14     int i=0, j=0,index=0,temp;
15     scanf("%d",&temp);
16     while(index<mpos){//index的值表示当前位置待填,mpos是目标index
17         if(a[i]<=temp)i++;index++;
18         else{
19             j++;index++;
20             if(j==len2)temp=INF;
21             else scanf("%d",&temp);
22         }
23     }
24     if(a[i]<=temp) printf("%d",a[i]);
25     else printf("%d",temp);
26     return 0;
27 }

 

posted on 2019-02-28 16:15  Vitavi  阅读(86)  评论(0编辑  收藏  举报

导航