找出数组中下一个大数

23 篇文章 0 订阅
10 篇文章 0 订阅

给出一整数数组,找出比当前元素大的下一个数。


Array on integer is given
find out next bigger number

Ex {2,5,3,4,6,1}
Out: 2->5
5->6
3->4
4->6
6->-1 //not possible

1-> -1 //not possible

算法时间和空间复杂度都为O(n)

用栈来维护数组的下标。



O(n) time and O(n) space algorithm

Maintain a stack

1.start from the first element.push it's position into the stack
2.now check the second element with top of stack.if it is greater pop the stack and set its value to this second element.
else push this element to the stack.
3.do the same for rest of the elements.
4.elements left in the end are set to -1
Note:pop is to be performed till either stack is empty or top is stack is greater than current element

int a[6] = {2,5,3,4,6,1};

    for (int i = 0;i < 6; i++)
    {
        cout << a[i] << endl;
    }
    cout << endl;
    vector<int> nNum;
    nNum.push_back(0);
    //遍历数组中的元素
    for(int i = 1; i< 6; i++)
    {
        //当此元素大于栈顶下标表示代表的元素时 表示此元素是下一个大数
        while (nNum.size() && a[i] > a[nNum.back()])
        {
            //栈中的元素下标出栈,同时依据此下标给数组中的元素赋值,直到栈为空或者栈顶元素下标代表的元素大于a[i]
            a[nNum.back()] = a[i];
            nNum.pop_back();
        }
        nNum.push_back(i);
    }
    //给最后找不到next bigger number 的数赋值为-1
    while (nNum.size())
    {
        a[nNum.back()] = -1;
        nNum.pop_back();
    }
    for (int i = 0;i < 6; i++)
    {
        cout << a[i] << endl;
    }

这里用来存储next bigger number的数组可以新开辟一个。

想要处理更多的数,可以将数组和元素个数作为参数。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值