PAT A1029 Median(25 分)AC代码 成功解决内存超限

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 (≤2×10^5​​ ) 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

时间限制: 200ms
内存限制: 1.5MB
代码长度限制: 16KB

解题思路:

  1. 本题难点在于内存限制,如果将数据全部读入,内存会超限。
  2. 可以使用双针法,也可以合并两个数组然后再排序,但后者会出现内存超限。
  3. 另外,在每一组数据最后可以放置一个int最大值,以防有一个数组所有值比另一个都大,导致数组访问超限。

AC:使用双针法,第二个数组数据边读边进行

#include <cstdio>
#include <cstdlib>

const int INF = 0x7fffffff;
int main() {
    int l1, l2, i, j, count = 0;
    int *a1, a2;

    scanf("%d", &l1);
    a1 = (int *)malloc((l1 + 1) * sizeof(int));
    for (i = 0; i < l1; i++)
        scanf("%d", a1 + i);
    *(a1 + l1) = INF;
    scanf("%d", &l2);
    //a2 = (int *)malloc((l2 + 1) * sizeof(int));
    //for (i = 0; i < l2; i++)
    //  scanf("%d", a2 + i);
    //*(a2 + l2) = INF;

    int mid = (l1 + l2 - 1) / 2;            // l1 = mediapos
    i = j = 0;
    scanf("%d", &a2);
    while (count < mid)
    {
        if (*(a1 + i) < a2) i++;
        else {
            j++;
            if (j < l2)
            {
                scanf("%d", &a2);
            }
            else if (j == l2)
                a2 = INF;
            else
                break;
        }
        count++;
    }

    printf("%d\n", *(a1 + i) < a2 ? *(a1 + i) : a2);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/fried123123/article/details/81351706