c++ - 查找所有元素的数组中最新最小元素的位置
问题描述
对于整数元素数组,我想计算小于该元素的最新元素的位置(如果可能),否则将 -1 存储在该位置。
通过最新元素,我的意思是最大可能的索引小于当前索引。
例如。
(基于 0 索引)
让problem[5] = {4,7,1,3,8}
然后溶胶array = {-1,0,-1,2,3}
现在我能够以 O(n^2) 的时间复杂度做到这一点......但我无法在低于这个时间复杂度的情况下做到这一点。所以,谁能告诉我如何在小于 O(n^2) 的时间复杂度内做到这一点。
我的 n^2 时间复杂度代码:
int n = 5;
int ques[n] = {4, 7, 1, 3, 8};
int sol[n] = { -1, -1, -1, -1, -1};
for (int i = 1; i < 5; i++) {
int pos;
for (int j = 0; j < i; j++) {
pos = -1;
if (ques[j] < ques[i]) {
pos = j;
}
}
sol[i] = pos;
}
for (int i = 0; i < n; i++){
cout << sol[i] << ' ';
}
解决方案
您可以利用堆栈数据结构,其中包含等待较小前体的元素索引。方法是线性的。
Make a stack `S`
Scan array `Q[]` from the end
while (Q[i] < Q[S.top()])
t = S.Pop()
Sol[t] = i
Push i onto stack
Write -1 into Sol[] for all indices remaining in the stack
代码
#include <iostream>
#include <stack>
using namespace std;
int main() {
int n = 5;
int ques[] = { 4, 7, 1, 3, 8 };
int sol[] = { -1, -1, -1, -1, -1 };
stack<int> s;
for (int i = n - 1; i >= 0; i--) {
while (s.size() > 0 && ques[i] < ques[s.top()]) {
int t = s.top();
sol[t] = i;
s.pop();
}
s.push(i);
}
for (int i = 0; i < n; i++)
cout << sol[i] << ' ';
推荐阅读
- javascript - JavaScript 在浏览器中提取 zip 文件并呈现为文件系统
- oracle - 从 sqlcl 运行 liquibase 更新时找不到 SQL 文件
- javascript - 如何找到一个与另一个值异或的值?
- java - 总和为给定数字的子集计数(允许重复)。没有得到正确的输出
- iis - IIS 10 中的重定向问题
- string - 如何将 AnsiStr 转换为字节,反之亦然?
- c# - 如何在本地测试/运行 azure times 功能
- javascript - 电子中的请求单实例锁定方法总是返回真
- keras - Keras LSTM 网络预测与输入一致
- java - 如何在 Mac 上删除 java.util.prefs 存储?