1. 程式人生 > >查詢陣列第二大數

查詢陣列第二大數

#include <algorithm>#include <assert.h>#include <iostream>#include <random>#include <time.h>#include <vector>
using namespace std;//演算法本體
const int *FindSecondBigNum(const vector<int>&kvec){ if (kvec.size() < 2) { return nullptr; } std::pair<
const int *, const int *> kPair; kPair.first = kvec[0] > kvec[1] ? &kvec[0] : &kvec[1]; kPair.second = kvec[0] < kvec[1] ? &kvec[0] : &kvec[1];
for (int i = 2; i < kvec.size(); ++i) { if (*kPair.first <= kvec[i]) { kPair.second = kPair.first
; kPair.first = &kvec[i]; } else if (*kPair.second <= kvec[i]) { kPair.second = &kvec[i]; } }
return kPair.second;}//作為演算法的驗證
int GetSecondBigNum(const vector<int>&kvec){ if (kvec.size() < 2) { return 0; }
vector<
int> tmp(kvec.begin(), kvec.end()); sort(tmp.begin(), tmp.end(), [](const int a, const int b) { return a > b; });
return tmp[1];}
void RandomArray(vector<int>&kvec,constint length){ if (length <= 0) return;
kvec.resize(length);
srand((unsigned)time(nullptr)); for (int i = 0; i < length; i++) { kvec[i] = rand() % 100; }}
template <typename T>ostream &operator<<(ostream &ostr, const vector<T> &vec){ for (size_t i = 0; i < vec.size(); i++) { cout << "Array[" << i << "]=" << vec[i] << endl; } return ostr;}
int main(){ vector<int> vec1;
const int length = 100;
for (int i = 0; i < 10000; i++) { RandomArray(vec1, length);
int a1 = GetSecondBigNum(vec1);
int b1 = *FindSecondBigNum(vec1);
if (a1 != b1) { cout << "err:a1=" << a1 << " b1=" << b1 << endl; cout << "Array:" << endl; cout << vec1 << endl; } }
return 1;}