zoukankan      html  css  js  c++  java
  • 1029 Median

    题目链接:Median

    Given an increasing sequence S of N integers, the median is the number at the middle position. For example, the median of S1 = { 11, 12, 13, 14 } is 12, and the median of S2 = { 9, 10, 15, 16, 17 } is 15. The median of two sequences is defined to be the median of the nondecreasing sequence which contains all the elements of both sequences. For example, the median of S1 and S2 is 13.

    Given two increasing sequences of integers, you are asked to find their median.

    Input Specification:

    Each input file contains one test case. Each case occupies 2 lines, each gives the information of a sequence. For each sequence, the first positive integer N (≤) is the size of that sequence. Then N integers follow, separated by a space. It is guaranteed that all the integers are in the range of long int.

    Output Specification:

    For each test case you should output the median of the two given sequences in a line.

    Sample Input:

    4 11 12 13 14
    5 9 10 15 16 17
    
     

    Sample Output:

    13

    最终AC代码如下:

    #include <bits/stdc++.h>
    using namespace std;
    int main(){
        int i, j, t, a, b, len;
        vector<int> va, vb;
        cin >> a;
        for(i=0; i<a; i++){
            scanf("%d", &j);
            va.push_back(j);      
        }
        cin >> b;
        for(i=0; i<b; i++){
            scanf("%d", &j);
            vb.push_back(j);      
        }
        t = min(va[0], vb[0]);
        len = (a + b + 1) >> 1; //除2 len表示两个指针需要移动的次数和
        for(i=0, j=0; i+j < len; ){ 
            if(i >= a) t = vb[j++]; //说明va已经遍历完 直接在vb在找 
            else if(j >= b) t = va[i++]; //说明vb已经遍历完 直接在va在找 
            else if(va[i] > vb[j]) t = vb[j++]; //将较小的赋值给 t 
            else t = va[i++];
        }
        printf("%d
    ", t);
        return 0;
    }

    总结:主要思想是,将数据存在两个不同的向量里~这里不放在一个向量里,是因为输入的两组数据都是单调不减的,而且由于涉及大数据量,因此不能排序但是采用向量存储,然后用STL自带的sort排序也行),于是要好好利用这个性质。然后,将i、j两个变量视为向量上的指针,循环作比较、赋值、移动三个动作。这里需要每一步将当轮比较的较小值存在变量 t 中,不然退出for循环后,就不知道是该输出的是哪个数组上的值了。

    有一个需要注意的极端情况:可能两组数据的数量极端不匹配,一个数组上的指针都到末端了,还没找到中值。我的处理方式是,每次比较两个数组前,都得判断一下指针的范围,若某个指针超出范围,则直接在另一个数组上找;否则,比较指针当前所指值的大小。

    我看PAT上,这个题的通过率很低,或许大家都把这个问题想复杂了,又或许在追求时间复杂度尽可能低~换个角度,简单粗暴地用最直白的方式理解这个题,那么或许不会觉得这个题很难了吧。即:在两个单调不减数组中,找他们的中位数,那么不就是一一比较,直到找到中位数呗。

  • 相关阅读:
    任务调度之Quartz.Net配置文件
    任务调度之Quartz.Net可视化界面
    任务调度之Quartz.Net基础
    Asp.Net Core中完成拒绝访问功能
    Asp.Net Core Identity中基于角色授权
    Javascript 继承 图形化展示
    Try,Catch,Finally三块中如果有Return是怎么个运行顺序
    Autofac 一个使用Demo
    Autofac
    WCF代理是怎么工作的?用代码说话
  • 原文地址:https://www.cnblogs.com/heyour/p/12810181.html
Copyright © 2011-2022 走看看