找出数组中下一个大数

来源:互联网 发布:网卡mac地址修改器 编辑:程序博客网 时间:2024/06/05 11:29

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


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的数组可以新开辟一个。

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


原创粉丝点击