496. Next Greater Element I
来源:互联网 发布:软件开发培训多久 编辑:程序博客网 时间:2024/06/18 05:56
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
andnums2
are unique. - The length of both
nums1
andnums2
would not exceed 1000.
My method:
class Solution {public: vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) { unordered_map<int,int> nextMax; stack<int> s; for (int n:nums) { while (!s.empty() && s.top()<n) { nextMax[s.top()]=n; s.pop(); } s.push(n); } vector<int> ans; for (int i:findNums) { if (!nextMax.count(i)) ans.push_back(-1); else ans.push_back(nextMax[i]); } return ans; }};
class Solution {public: vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) { vector<int>res; int findNums_size = findNums.size(),nums_size= nums.size(); for(int i = 0; i <findNums_size; i++){ int next = 1001, equ = 0; for(int j = 0; j<nums_size; j++){ if(nums[j]==findNums[i]) equ=1; if(nums[j]>findNums[i]&&equ==1){ next = nums[j]; break; } } if(next ==1001){ res.push_back(-1); }else res.push_back(next); } return res; }};
the more effective method:
阅读全文
0 0
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496.Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 496. Next Greater Element I
- 二维码保存本地及上传实现
- 用xml充当小型数据库案例
- 理解Angular中的$apply()以及$digest()
- javascript es6 编程风格
- 过河
- 496. Next Greater Element I
- mysql处理高并发,防止库存超卖
- android 常用控件--ImageView
- 过河(状压dp典型题)
- 多线程
- Picasso使用简介及分析(2)
- USB协议中的返回包含义
- Linux下Joomla手动删除安装目录
- 设计模式学习:适配器