本文共 3201 字,大约阅读时间需要 10 分钟。
目的:使用STL的vector模板设计并实现顺序表应用场合的一些简单算法设计。
应用7:一个长度为L(L>=1)的升序序列S,处在第[L/2]个位置的元素称为S的中位数。例如,若序列S1 = (11,13,15,17,19),则S1的中位数为15。两个序列的中位数是含它们所有元素的升序序列的中位数。例如,若序列S2 = (02,04,06,08,20),则S1和S2的中位数为11。假设以两个元素依值递增有序排列的线性表A和B分别表示两个升序序列(即同一表中的元素值各不相同),现要求设计在时间和空间两方面都尽可能高效的算法,找出两个长度相同的升序序列A和B的中位数。
参考函数原型:templateElemType Search_Mid( const vector &A, const vector &B );
第一行:有序序列的长度
第二行:有序序列A的数据元素(数据元素之间以空格分隔)
第三行:有序序列B的数据元素(数据元素之间以空格分隔)
第一行:序列A的遍历结果
第二行:序列B的遍历结果
空行
第三行:序列A和B的中位数
511 13 15 17 1902 04 06 08 20
11 13 15 17 19 02 04 06 08 20 11
按照思路二,不用暴力法求解,得到的结果如上。有一个样例没有通过的。根据中位数的特性,盲猜有两种情况,一种是最终综合的向量的数量是偶数的,另外一种综合的向量元素数量是奇数
综合向量元素个数是偶数
综合向量元素个数是奇数
#include#include using namespace std;/* description:show all the elements of the vector*/template void show(vector & A){ typename std::vector test = A; typename std::vector ::iterator iter; for(iter = test.begin();iter != test.end();iter ++) { cout<<*iter<<" "; } cout< void inputElemType(vector &A,int size){ ElemType temp; for(int i = 0; i < size;i ++) { cin>>temp; A.at(i) = temp; }}/* description:with the ordered sequence,search the two elements which add up to target*/template int getCount(const vector &A1, int sum ){ //the paramenter is const ,cannot get the reference to the A1 vector A(A1); // using vector to imitate the hashmap vector VectorHash; VectorHash.assign(sum + 1,0); typename std::vector ::iterator iterB = A.begin(); while(iterB != A.end()) { VectorHash.at(*iterB) = 1; iterB ++; } //calculate the the number of the pairs int count = 0; int target = sum + 1; iterB = A.begin(); while(iterB != A.end()) { VectorHash.at(*iterB) = 0; if(VectorHash.at(target - *iterB) == 1) { count ++; VectorHash.at(target - *iterB) = 0; } iterB ++; } show(A); cout< >length; int maxEdge; cin>>maxEdge; vector test(length); inputElemType(test,length); cout< <
这里是有问题的,我自己设想他会删除重复元素,但是实际上并没有删除的重复的元素。而是将所有的元素的都插入其中,在两个序列的综合序列中对两个序列的所有元素进行的排序,即使重复不删除
转载地址:http://owwvb.baihongyu.com/