找出数组中下一个大数
来源:互联网 发布:网卡mac地址修改器 编辑:程序博客网 时间:2024/06/05 11:29
给出一整数数组,找出比当前元素大的下一个数。
Array on integer is given
find out next bigger number
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的数组可以新开辟一个。
想要处理更多的数,可以将数组和元素个数作为参数。
- 找出数组中下一个大数
- 写一个函数,找出一个整数数组中的第二大数
- 快速找出一个数组中的最大数、第二大数
- 快速找出一个数组中的最大数和第二大数
- 快速找出一个数组中的最大数、第二大数。
- 如何快速找出一个数组中最大数和第二大数
- [基础题]1.快速找出一个数组中的最大数、第二大数。
- 分治法找出数组中第二大数
- 找出整数数组中第二大数
- 找出一个数组中的”单身“
- 一次遍历找出整型数组中第二大数
- 快速找出数组中的最大数和第二大数
- 找出一个二维数组里的鞍点
- 找出一个二维数组中的鞍点
- 找出一个无序数组的中位数
- 一个数组中第一大数和第二大数
- 求一个数组中的最大次大数
- 求一个数组中第二大数...
- Chakra Linux 安装指南(二):Chakra Linux 安装
- 把长的数字用逗号隔开显示(千分位)
- 队列
- js中数组的创建和删除
- Frequently Asked Questions Chakra是否使用Pacman作为包管理器
- 找出数组中下一个大数
- POJ 1837 Balance
- HDU 1051 Wooden Sticks(LIS)
- Linux下配置JDK以及报cannot restore segment prot after reloc: Permission denied错解决方案
- 怎么搭建公司内部Maven服务器
- Python Challenge 02 Solution
- JS中数组Array的用法{转载}
- git 思维导图
- UVA 11729(Commando War-按执行时间贪心)