《Cracking the Coding Interview程序员面试金典》----下一个元素(下一个比他大的)
来源:互联网 发布:淘宝店铺怎么上众划算 编辑:程序博客网 时间:2024/05/17 05:19
时间限制:3秒 空间限制:32768K 热度指数:740
算法知识视频讲解题目描述
现在我们有一个int数组,请你找出数组中每个元素的下一个比它大的元素。
给定一个int数组A及数组的大小n,请返回一个int数组,代表每个元素比他大的下一个元素,若不存在则为-1。保证数组中元素均为正整数。
测试样例:
[11,13,10,5,12,21,3],7
返回:[13,21,12,12,21,-1,-1]
思路:最右边的那个值肯定没有最大值,所以肯定是-1。初始栈为-1。从后向前计算:
(1)如果当前元素大于栈顶元素,则栈顶元素退出,如果还是大于栈顶元素,继续退出,一直遍历栈到-1或者小于栈顶元素。这个元素就是就是当前值的下一个比较大的元素。
(2)如果当前元素小于栈顶元素,栈顶元素就是当前值的下一个比较大的元素
代码如下:
#include<iostream>#include<vector>#include<map>#include<queue>#include<algorithm>#include<set>#include<stack>using namespace std;vector<int> findNext(vector<int> A, int n) {stack<int> s;s.push(-1);int sz = A.size();vector<int> res(sz);int top;for (int i = sz - 1; i >= 0; --i){top = s.top();while (top != -1 && A[i] >= top){s.pop();top = s.top();}s.push(A[i]);res[i] = top;}return res;}void printVector(vector<int>mat, int n){for (int j = 0; j < n; j++){cout << mat[j] << " ";}cout << endl;}int main(){vector<int> v;int m;int temp;while (cin >> m){v.clear();for (int j = 0; j < m; j++){cin >> temp;v.push_back(temp);}printVector(findNext(v, m), m);}return 0;}
不懂的可以加我的QQ群:261035036(IT程序员面试宝典
群) 欢迎你的到来哦,看了博文给点脚印呗,谢谢啦~~
0 0
- 《Cracking the Coding Interview程序员面试金典》----下一个元素(下一个比他大的)
- 《Cracking the Coding Interview程序员面试金典》----下一个较大元素(所有比他大中最小的)
- cracking the coding interview 中文版 (程序员面试金典)
- cracking the coding interview 中文版 (程序员面试金典)
- cracking the coding interview 中文版 (程序员面试金典)
- 《Cracking the Coding Interview程序员面试金典》----空格替换
- 《Cracking the Coding Interview程序员面试金典》----像素翻转
- 《Cracking the Coding Interview程序员面试金典》----清除行列
- 《Cracking the Coding Interview程序员面试金典》----实时中位数
- 《Cracking the Coding Interview程序员面试金典》----词频统计
- 《Cracking the Coding Interview程序员面试金典》----数字发音
- 《Cracking the Coding Interview程序员面试金典》-----
- 《Cracking the Coding Interview程序员面试金典》----C++重载>>和<<(输入输出运算符)
- 《Cracking the Coding Interview程序员面试金典》----最大字母矩阵(字母相同)
- 《Cracking the Coding Interview程序员面试金典》----最大子方块(寻找01)
- 《Cracking the Coding Interview程序员面试金典》----字符串变换(字典树)
- 《Cracking the Coding Interview程序员面试金典》----另类加法(不得使用+-x/运算符号)
- 《Cracking the Coding Interview程序员面试金典》----确定字符互异
- yii查询相关
- 坚持#第178天~录屏是个双倍神符,学知识超快,能够提升自己、别忘了学以致用,有什么好害羞的!
- 图的储存之邻接矩阵
- hdu5971 Wrestling Match(染色法判二分) 2016ACM/ICPC亚洲区大连站
- Tensorflow学习: RNN-LSTM应用于MNIST数据分类
- 《Cracking the Coding Interview程序员面试金典》----下一个元素(下一个比他大的)
- HDU
- fasterxml如何对Java枚举类型做类型转换
- httpclientpost网络获取数据
- [Android] Android Studioの打包问题
- rpm,diff,patch,grep,cut,sort,tr
- QT小知识点(3) -Qt Creator 使用技巧之提高编译速度【使用jom参数】
- Windows中hosts文件的位置
- myeclipse:could not create..异常处理