查看更多知识: www.daydayxuexi.com
问题描述:一个int数组,里面数据无任何限制,要求求出所有这样的数a[i],其左边的数都小于等于它,右边的数都大于等于它。
能否只用一个额外数组和少量其它空间实现。
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 1, 2, 3, 2, 3, 4, 5, 6, 7, 3, 2, 3, 9};
int max = arr[0];
int min = arr[sizeof(arr)/sizeof(arr[0]) - 1];
bool *result = new (nothrow) bool[sizeof(arr)/sizeof(arr[0])];
if (NULL == result) {
cout << "new err" << endl;
return 0;
}
for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); ++i) {
result[i] = false;
}
cout << "原始数据: ";
for (int i = 0; i< sizeof(arr)/sizeof(arr[0]); ++i) {
cout << arr[i] << " ";
}
cout << endl;
//对数组中每一个数判断其左半部分是否满足
for (int i = 0, j = 0; i < sizeof(arr)/sizeof(arr[0]); ++i) {
while (j < i) {
if (max < arr[i]) {
max = arr[i];
}
++j;
}
if (arr[i] >= max) {
result[i] = true;
}
}
cout << "比左面都不小的: ";
for (int i = 0; i< sizeof(arr)/sizeof(arr[0]); ++i) {
cout << result[i] << " ";
}
cout << endl;
//对数组中每一个数判断其右半部分是否满足
for (int i = sizeof(arr)/sizeof(arr[0]) - 1, j = sizeof(arr)/sizeof(arr[0]) - 1; i >= 0; --i) {
while (j >= i) {
if (min > arr[i]) {
min = arr[i];
}
--j;
}
if (arr[i] > min) {
result[i] = false;
}
}
cout << "比右面都不大的: ";
for (int i = 0; i< sizeof(arr)/sizeof(arr[0]); ++i) {
cout << result[i] << " ";
}
cout << endl;
cout << "最终结果: ";
for (int i = 0; i< sizeof(arr)/sizeof(arr[0]); ++i) {
if (result[i]) {
cout << arr[i] << " ";
}
}
}