- 暴力求解 【14/25分】
#include <bits/stdc++.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
const int maxn = 100010;
int main(int argc, char** argv) {
int n, num[maxn] = {0}, res[maxn], count=0;
cin >> n;
for(int i = 0; i < n; i++){
cin >> num[i];
}
bool flag = false;
int m = 0;
int ans = 0;
for(int i = 0; i < n; i++){
int j;
ans = 0;
if(i == 0){
for(j = 1; j < n; j++){
if(num[j] > num[i]){
ans++;
continue;
} else {
break;
}
}
} else if( i == n-1){
for(j = 0; j < n-1; j++){
if(num[j] < num[i]){
ans++;
continue;
} else {
break;
}
}
} else {
for(j = 0; j < i; j++){
if(num[j] < num[i]){
ans++;
continue;
} else {
break;
}
}
for(j = i+1; j < n; j++){
if(num[j] > num[i]){
ans++;
continue;
} else {
break;
}
}
}
if(ans == n-1){
count++;
res[m++] = num[i];
}
}
cout << count<< endl << res[0];
for(int i = 1; i < count; i++){
cout << " " << res[i];
}
return 0;
}
- 满分代码
统计从左往右当前位前最大的数,以及从右往左当前位最小的数字。
#include <bits/stdc++.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
const int maxn = 100010;
const int INF = 0x3fffffff;
int main(int argc, char** argv) {
int n, num[maxn] = {0}, res=0;
int leftMax[maxn], rightMin[maxn], ans[maxn];
cin >> n;
for(int i = 0; i < n; i++){
cin >> num[i];
}
leftMax[0] = 0;
for(int i = 1; i < n; i++){
leftMax[i] = max(leftMax[i-1], num[i-1]);
// cout << "lett:::::" << leftMax[i] << endl;
}
rightMin[n-1] = INF;
for(int i = n-2; i >= 0; i--){
rightMin[i] = min(rightMin[i+1], num[i+1]);
// cout << "right:::::" << rightMin[i] << endl;
}
for(int i = 0; i < n; i++){
if(num[i] > leftMax[i] && num[i] < rightMin[i]){
ans[res++] = num[i];
}
}
cout << res << endl ;
for(int i = 0; i < res; i++){
cout << ans[i];
if(i!=res-1){
cout << " ";
}
}
cout << endl;
return 0;
}