【趣味算法题】在数组中,对于所有元素,找出比当前元素大的下一个元素

在数组中,对于所有元素,找出比当前元素大的下一个元素

意思就是,eg.  数组为     3 1 2 5 4 6 7

那么我们需要得到的结果应该是  5 2 5 6 6 7 -1

 

解决方法如下:

 

  1. 暴力匹配: O (n ^ 2 ) 的效率对所有元素匹配过去,效率非常的低
  2. 经过提示, 我想到的一种 O ( nlg n ) 效率的算法

  只需要对数组扫描一次,我们用一个 Priority_queue 来得到当前最小的元素

  Prority_queue 存放的数据结构为:

struct sc {
    int key, flag;
    bool operator < (const sc & a) const
    { return a.key < key; }
};

  key 表示元素的值, flag 表示下标,在赋值的时候有用

 

  算法思路:

  遍历一遍,如果当前队列为空,那么 push

  否则,如果队首的最小元素小于 a[i]

    那么在 答案数组中赋值即得到比当前元素大的下一个元素

    如果队列空,break

 

My source code:

#include <iostream>
#include <cstring>
#include <stack>
#include <string>
#include <ctime>
#include <queue>
#include <algorithm>

using namespace std;

const int MAXN = 1000;

int a[MAXN], b[MAXN];

struct sc {
    int key, flag;
    bool operator < (const sc & a) const
    { return a.key < key; }
};


int main () {
    int i, j, k, u, v, n;
    memset (b, -1, sizeof (b));

    cin >> n;
    for (i = 0; i < n; ++i) cin >> a[i];
    priority_queue <sc> que;
    for (i = 0; i < n; ++i) {
        if (que.empty ()) {
            sc temp;
            temp.key = a[i], temp.flag = i;
            que.push (temp);
            continue;
        }
        for (;;) {
            if (que.empty())    break;  //if pop to empty break;

            if (que.top ().key < a[i]) {
                b[que.top ().flag] = a[i];
                que.pop ();
            } else break;
        }
        sc temp;
        temp.key = a[i];
        temp.flag = i;
        que.push (temp);
    }
    for (i = 0; i < n; ++i) {
        cout << a[i] << ' ';
    }
    cout << endl;
    for (i = 0; i < n; ++i) {
        cout << b[i] << ' ';
    }
    cout << endl;


    return 0;
}

 

posted @ 2015-05-04 09:31  Jeremy Wu  阅读(793)  评论(1编辑  收藏  举报