今日头条面试算法题

题目:给定一个整形数组,数组是无重复随机无序的,要求打印出所有元素左边第一个大于该元素的值。

#include <iostream>
#include <time.h>
#include <stack>
using namespace std;

void shuffle(int a[], int n)
{
    srand(time(NULL));
    for(int i = 0; i < n; i++)
    {
        int index = rand() % n;
        int tmp = a[i];
        a[i] = a[index];
        a[index] = tmp;
    }
}

void f(int a[], int n)
{
    stack<int> s;
    if(n <= 1)
        return;

    s.push(a[0]);
    for(int i = 1; i < n; i++)
    {
       while(!s.empty() && a[i] > s.top())
       {
            cout<<s.top()<<','<<a[i]<<endl;
            s.pop();
       }

       s.push(a[i]);
    }
}

int main(int argc, char *argv[])
{
    int *a = new int[atoi(argv[1])];
    for(int i = 0; i < atoi(argv[1]); i++)
    {
        a[i] = i + 1;
    }
    shuffle(a, atoi(argv[1]));
    for(int i = 0; i < atoi(argv[1]); i++)
    {
        cout<<a[i]<<' ';
    }
    cout<<endl;
    cout<<"------------------------------"<<endl;

    f(a, atoi(argv[1]));
    return 0;
}

    原文作者:菜鸟懿
    原文地址: https://blog.csdn.net/coder_yi_liu/article/details/71554123
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞