【LeetCode】496 Next Greater Element I
来源:互联网 发布:vscode c 开发环境 编辑:程序博客网 时间:2024/06/01 10:32
原题地址:496. Next Greater Element I。
解法一:普通解法
//O(n * m)vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) { vector<int>::iterator pos; vector<int> res; int flag; for (int i = 0; i < findNums.size(); i++) { pos = find(nums.begin(), nums.end(), findNums[i]); flag = 0; for (vector<int>::iterator j = pos + 1; j != nums.end(); j++) { if (*j > findNums[i]) { res.push_back(*j); flag = 1; break; } } if (flag == 0) { res.push_back(-1); } } return res;}
解法二:栈解法
使用一个栈来保存递减子序列,当遇到一个数nums[i]
大于栈顶元素时,则弹出所有小于nums[i]
的元素,并且将他们的Next Greater Element
设为nums[i]
,随后将nums[i]
压栈。
如图所示,nums
为[5, 4, 3, 2, 1, 6]
,6是前面所有元素[5, 4, 3, 2, 1]
的Next Greater Element
。
再比如nums
为[9, 8, 7, 3, 2, 1, 6]
,栈首先会保存一个递减子序列[9, 8, 7, 3, 2, 1]
,然后我们看见6大于1,则弹出1 2 3
, 他们的Next Greater Element
就应该是6。
// O(n)vector<int> nextGreaterElement2(vector<int>& findNums, vector<int>& nums) { vector<int> res; stack<int> s; unordered_map<int, int> map; for (int i = 0; i < nums.size(); i++) { while (!s.empty() && s.top() < nums[i]) { map[s.top()] = nums[i]; s.pop(); } s.push(nums[i]); } for (int i = 0; i < findNums.size(); i++) { if (map.count(findNums[i]) > 0) { res.push_back(map[findNums[i]]); } else { res.push_back(-1); } } return res;}
参考:
Java 10 lines linear time complexity O(n) with explanation
阅读全文
0 0
- leetcode-496-Next Greater Element I
- Leetcode #496 Next Greater Element I
- leetcode[496]:Next Greater Element I
- 【LeetCode】496 Next Greater Element I
- leetcode 496 Next Greater Element I
- LeetCode 496 Next Greater Element I
- LEETCODE--Next Greater Element I
- [LeetCode] Next Greater Element I
- LeetCode:Next Greater Element I
- 【leetcode】Next Greater Element I
- LeetCode Next Greater Element I
- Next Greater Element I(leetcode)
- LeetCode-Next Greater Element I
- LeetCode 496: Next Greater Element I (下一个大的元素)
- LeetCode.496(503、556) Next Greater Element I && II && III
- 【Leetcode】496. Next Greater Element I
- leetcode -- 496. Next Greater Element I 【栈】
- 【LeetCode】496. Next Greater Element I
- 比赛
- Centos下 rpm 打补丁,patch
- 西电2017网信实验班选拔
- anaconda
- windows/vs如何获取程序内存使用量和时间花费
- 【LeetCode】496 Next Greater Element I
- Link16战术数据链的基础知识
- 记录一下matplotlib的使用。
- 希尔排序的介绍与分析
- BZOJ 1098: [POI2007]办公楼biu
- servlet
- 百度地图marke
- 二、基于Cortex-A8和ZigBee技术的智能家居监控系统的设计与实现
- Android图片处理框架之Picasso学习使用