Next Greater Element I
来源:互联网 发布:职业女装 知乎 编辑:程序博客网 时间:2024/05/16 17:26
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1’s elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For number 2 in the first array, the next greater number for it in the second array is 3.
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
Note:
All elements in nums1 and nums2 are unique.
The length of both nums1 and nums2 would not exceed 1000.
方法: 利用栈和映射。
class Solution {public: vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) { stack<int> st; unordered_map<int,int> mp; for(int i = 0 ; i < nums.size() ; ++i){ while(!st.empty() && st.top() < nums[i]){ mp[st.top()] = nums[i]; st.pop(); } st.push(nums[i]); } vector<int> res; for(int i = 0 ; i < findNums.size(); ++i) res.push_back( mp.count(findNums[i]) > 0? mp[findNums[i]]: -1 ); return res; }};
- Next Greater Element I
- Next Greater Element I
- Next Greater Element I
- Next Greater Element I
- Next Greater Element I
- Next Greater Element I
- Next Greater Element I
- Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- LEETCODE--Next Greater Element I
- [LeetCode] Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- LeetCode:Next Greater Element I
- 【leetcode】Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 逻辑回归模型介绍和程序实现
- 贪心算法为什么就是经典?
- win10 版本下的ZWMAX完全安装方法之更改UCG
- 计算机科学和编程导论-week3-对象
- 搞懂js继承方法
- Next Greater Element I
- 【学习笔记(JAVA从入门到精通)】Java数据类型&操作符【内含问题,Mark】
- 矩阵与斐波那契数列
- 搭建三层架构
- Another Server(语文功底题)
- 深度学习小白——Alexnet之tensorflow实现
- 消息总线能否实现消息必达?
- uml中的各种符号表示什么意义与关系
- 写给初学者24_android_数据持久化_共享参数_SharedPreferences