【问题标题】:FInd position of latest smallest element in the array for all elements查找所有元素的数组中最新最小元素的位置
【发布时间】:2020-05-19 07:25:41
【问题描述】:

对于整数元素数组,我想计算小于该元素的最新元素的位置(如果可能),否则将 -1 存储在该位置。

最新元素是指最大可能的索引小于当前索引。

例如。

(基于 0 索引)

problem[5] = {4,7,1,3,8}

那么 sol 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] << ' ';

}

【问题讨论】:

  • 你的意思是“[5] = {4,7,3,1,8} 然后 sol array = {-1,0,-1,-1 ,3}" ?
  • 您能否与我们分享 O(n^2) 的解决方案以及您尝试以较低的复杂性解决问题的一些尝试?
  • 我很抱歉!!我在问题中进行了编辑。
  • 请不要对这个问题投反对票……我是编程社区的新手。
  • 投票不支持你。他们是为了这个问题。它们是衡量我们认为这个问题写得好、有趣和对社区有多大帮助的衡量标准。无论如何,自从您编辑了问题后,我删除了我的反对票。

标签: c++ arrays c++14


【解决方案1】:

您可以利用堆栈数据结构,其中包含等待较小前体的元素索引。方法是线性的。

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] << ' ';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-18
    • 2017-01-17
    • 2014-07-21
    • 2013-12-15
    • 1970-01-01
    • 2021-12-27
    • 2013-11-21
    • 2018-10-17
    相关资源
    最近更新 更多