例如,序列:3, 4, 2, 5, 8, 9, 10 输出:8,9,10 /* * Copyright (c) 2011 alexingcool. All Rights Reserved. */ #include <iostream> #include <algorithm> #include <vector> #include <iterator> using namespace std; #define INF 65535 int array[] = {3, 4, 2, 5, 8, 9, 10}; const int size = sizeof array / sizeof *array; void tranverse(int (&array)[size], vector<int> &result) { int leftMax[size]; int rightMin[size]; leftMax[0] = -INF; rightMin[size - 1] = INF; for(int i = 0; i < size - 1; i++) leftMax[i + 1] = max(array[i], leftMax[i]); for(int i = size - 1; i > 0; i--) rightMin[i - 1] = min(array[i], rightMin[i]); for(int i = 0; i < size; i++) { if(array[i] >= leftMax[i] && array[i] <= rightMin[i]) result.push_back(array[i]); } } //仔细看上面的代码之后,不难发现可以省去一个数组及一个循环 //达到时间和空间上的优化 void tranverse2(int (&array)[size], vector<int> &result) { int leftMax = -INF; int rightMin[size]; rightMin[size - 1] = INF; for(int i = size - 1; i > 0; i--) { rightMin[i - 1] = min(array[i], rightMin[i]); } for(int i = 0; i < size; i++) { if(array[i] >= leftMax) { leftMax = array[i]; if(array[i] <= rightMin[i]) result.push_back(array[i]); } } } void main() { vector<int> result; tranverse(array, result); copy(result.begin(), result.end(), ostream_iterator<int>(cout, " ")); cout << endl; }