(一)題目c++
題目連接:https://www.patest.cn/contests/pat-a-practise/1029數組
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.ide
Given two increasing sequences of integers, you are asked to find their median.測試
Inputspa
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 (<=1000000) 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.code
Outputorm
For each test case you should output the median of the two given sequences in a line.blog
Sample Input4 11 12 13 14 5 9 10 15 16 17Sample Output
13
——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
(二)題解
(1)題目意思已經很明確了,就是要尋找兩個有序數組合併成一個有序數組後中間的那個數。若是合併後數組長度爲偶數則輸出中間兩個數中左邊的那個。
於是尋找的數在合併後的下標應該是target = n % 2 ? n / 2 : n / 2 - 1;
(2)個人作法是設置兩個下標i,j分別對應s1數組和s2數組。i + j的值就很好的反映了合併後對應的下標。問題是如何標記當前位置是s1[i]仍是s2[j]?
期初我是設置了一個flag標記,flag爲0就認爲是s1[i]不然就認爲是s2[j]。測試發現這隻能反映上一輪的狀況,而不能決定最終的狀況。尤爲是當i或j走到頭的時候。。。
(3)給一些測試用例吧
Input1
4 1 1 1 1
5 2 2 2 2 2
Output1
2
Input2
5 1 2 3 4 5
4 1 6 7 8
Output2
4
Input3
6 1 1 1 1 1 10
5 2 2 2 2 2
Output 3
2
Input4
5 1 2 3 4 5
5 1 2 3 4 5
Output 4
3
(三)AC源碼
1 #include <bits/stdc++.h> 2 using namespace std; 3 #define maxn 1000005 4 #define For(I,A,B) for(int I = (A); I < (B); I++) 5 6 long long s1[maxn],s2[maxn]; 7 int n1,n2,n; 8 int main() 9 { 10 freopen("1029.in","r",stdin); 11 while(scanf("%d",&n1) != EOF) 12 { 13 For(i,0,n1) 14 scanf("%lld",&s1[i]); 15 scanf("%d",&n2); 16 For(i,0,n2) 17 scanf("%lld",&s2[i]); 18 n = n1 + n2; 19 int target = (n % 2) ? n / 2 : n / 2 - 1; 20 int i = 0,j = 0; 21 //bool flag = 0; 22 //cout<<target<<" !\n"; 23 while(i < n1 && j < n2 && i + j < target) 24 { 25 if(s1[i] < s2[j]) 26 { 27 i++; 28 //flag = 0; 29 } 30 else 31 { 32 j++; 33 //flag = 1; 34 } 35 //cout<<i<<" "<<j<<" "<<endl; 36 } 37 if(i + j < target) 38 { 39 while(i < n1 && i + j < target) 40 { 41 i++; 42 //flag = 0; 43 } 44 while(j < n2 && i + j < target) 45 { 46 j++; 47 //flag = 1; 48 } 49 } 50 //if(j == n2) j--; 51 //if(i == n1) i--; 52 if(j == n2 || (i != n1 && s1[i] < s2[j])) 53 { 54 printf("%lld\n",s1[i]); 55 } 56 else if(i == n1 || s1[i] >= s2[j]) 57 { 58 printf("%lld\n",s2[j]); 59 } 60 } 61 return 0; 62 }