【PAT甲級】1029 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 (≤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

題目大意

這題就是給出兩個有序的遞增數列,要求將兩個數列合併成一個非遞減數列,並輸出合併後的數列中位數,如果是偶數個則輸出第cnt/2個。

個人思路

這題其實用了算法筆記中的two points的思路,即對兩個數組從左到右對下標和下標對應的數字進行比較操作,選出較小的數加入合併數組,同時對被這個數字對應對數組下標+1,從左到右掃描一遍,如果某個源數組還有剩餘數字,則將剩下的直接加入合併數組。這題應該是通過源數組的數字數量來卡時間的,如果用二層循環做肯定會超時,所以要在o(n)的時間內完成合並。另外如果使用cin和cout可能會超時,所以記得用printf和scanf。

實現代碼

#include <cstdio>
#include <iostream>
#define ll long long
#define maxn 200005
using namespace std;

int main() {
    int n1, n2; // 數字個數
    int nums1[maxn], nums2[maxn], nums[maxn*2]; // 兩個有序數組和合並數組
    
    // input
    cin >> n1;
    for (int i = 0; i < n1; i ++) {
        scanf("%d", &nums1[i]);
    }
    cin >> n2;
    for (int i = 0; i < n2; i ++) {
        scanf("%d", &nums2[i]);
    }
    
    // 將兩個有序數組合併到至少一個數組合並完畢
    int index1 = 0, index2 = 0, cnt = 0;
    while (index1 < n1 && index2 < n2) {
        if (nums1[index1] <= nums2[index2]) {
            nums[cnt++] = nums1[index1++];
        }
        else {
            nums[cnt++] = nums2[index2++];
        }
    }
    
    // 將剩餘的數組合並
    while (index1 < n1) {
        nums[cnt++] = nums1[index1++];
    }
    while (index2 < n2) {
        nums[cnt++] = nums2[index2++];
    }
    
    // output
    if (cnt % 2 == 0)
        printf("%d\n", nums[cnt/2-1]);
    else
        printf("%d\n", nums[cnt/2]);
    
    return 0;
}

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章