程序分析:
首先,开辟一个栈s存放元素下标,开辟一个数组result存放每个数右边第一个比它大的元素。
(1) 如果栈为空或当前遍历的元素值array[index]小于等于栈顶的元素值array[s.top()],将index入栈并加1,指向下一个元素。反之,将array[index]赋给reault[s.top()],s的顶部元素出栈。
(2)重复操作步骤(1),直到index大于等于数组长度length,即遍历完所有元素。
(3)如果栈不为空,说明栈中保存的全是未找到右边第一个比它大的数组索引,我们依次将这些栈元素出栈,并赋值result[s.top()]=-1即可。
C++代码:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
int* FindMaxRight(int *array, int length) {
if (array == NULL) {
return array;
}
//开辟一个新空间,存放结果
int *result = new int[length];
//初始化一个栈,存放元素下标
stack<int>s;
int index = 0;//下标从0开始
while (index < length) {
//如果栈为空或栈顶元素大于等于指向元素
if (s.empty() || array[s.top()] >= array[index]) {
s.push(index++);
}
else {
//输出对应值并出栈
result[s.top()] = array[index];
s.pop();
}
}
//对于未匹配项,赋值为-1
while (!s.empty()) {
result[s.top()] = -1;
s.pop();
}
return result;
}
int main() {
int array[] = { 1,3,5,6,2,4 };
int length = sizeof(array) / sizeof(array[0]);
//输出原数组
cout << "The array is:";
for (int i = 0; i < length; i++) {
cout << array[i] << " ";
}
cout << endl;
//输出每个元素右边第一个比它大的元素的值
int *temp = FindMaxRight(array, length);
cout << "The first mmax number on the right is:";
for (int i = 0; i < length; i++) {
cout << *(temp+i) << " ";
}
cout << endl;
return 0;
}
C++运行结果: