注意点:
1.输入两行的方法
2.两行输入的数量和小于5的情况
1 //评测题目: 两个有序数组,找出最大的五个数字组成一个新的数组 2 #include <iostream> 3 #include <vector> 4 #include <cstring> 5 #include <bits/stdc++.h> 6 using namespace std; 7 8 vector<int> getTop5(vector<int>& data1, vector<int>& data2, int& up){ 9 int i=data1.size()-1; 10 int j=data2.size()-1; 11 vector<int> res; 12 for(int k=0; k<up;k++){ 13 if( i<0 || j<0 ) break; 14 if(data1[i] >= data2[j] ){ 15 res.push_back( data1[i] ); 16 i--; 17 } 18 else{ 19 res.push_back( data2[j] ); 20 j--; 21 } 22 } 23 24 if(res.size()<up){ //注意有可能不够5个。 25 if(i == -1 ){ 26 for(int m=j; res.size()<up && m>=0; m-- ){ 27 res.push_back( data2[m] ); 28 } 29 } 30 31 if(j == -1){ 32 for(int n=i; res.size()<up && n>=0; n-- ){ 33 res.push_back( data1[n] ); 34 } 35 } 36 } 37 38 return res; 39 } 40 41 int main(){ 42 43 int up = 5; 44 vector<int> data1; 45 vector<int> data2; 46 string str; 47 bool sign1=0; //代表data1已经读入 48 bool sign2=0; //代表data2已经读入 49 while( getline(cin, str) ){ 50 if(!sign1 ){ 51 istringstream temp1(str); 52 int cur1; 53 while(temp1>>cur1){ 54 data1.push_back(cur1); 55 } 56 sign1 = 1; 57 } 58 else if(!sign2 ){ 59 istringstream temp2(str); 60 int cur2; 61 while(temp2>>cur2){ 62 data2.push_back(cur2); 63 } 64 sign2 = 1; 65 } 66 67 if(sign1&&sign2) { 68 69 vector<int> res = getTop5(data1, data2, up); 70 if(res.size()<up) cout<<"nums are not enough "; 71 else{ 72 for(int i=0; i<up; i++){ 73 cout<<res[i]<<" "; 74 } 75 cout<<endl; 76 } 77 78 sign1 = 0; 79 sign2 = 0; 80 data1.clear(); 81 data2.clear(); 82 } 83 84 } 85 86 }