题目:
给你两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。
请你找出 nums1 中每个元素在 nums2 中的下一个比其大的值。
nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。
示例 1:
输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
输出: [-1,3,-1]
解释:
对于 num1 中的数字 4 ,你无法在第二个数组中找到下一个更大的数字,因此输出 -1 。
对于 num1 中的数字 1 ,第二个数组中数字1右边的下一个较大数字是 3 。
对于 num1 中的数字 2 ,第二个数组中没有下一个更大的数字,因此输出 -1 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/next-greater-element-i
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
方法1:数组1中遍历数组2的该元素右边的最大值,然后填值
方法2:维护一个单调递减栈,遍历nums2.当遍历的元素值A大于栈顶元素B时,弹出小于A的元素;
如果小于则入栈。
同时维护一个哈希表,每次弹出时,说明A即为第一个比B大的元素;将A和B的对应关系存入哈希表。
遍历完成后,num1根据hash表填入值。
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int len1 = nums1.length;
int len2 = nums2.length;
Deque<Integer> stack = new LinkedList<Integer> ();
Map<Integer, Integer> map = new HashMap<>();
int[] ans = new int[len1];
//special
if (nums1 == null || nums2 == null || len1 > len2) {
return ans;
}
for (int i = 0; i < len2; i++) {
while (!stack.isEmpty() && (nums2[i] > stack.peek ())) {
//根据值确定右边最大的值,保存对应关系
map.put (stack.pop(), nums2[i]);
}
stack.push (nums2[i]);
}
for (int i = 0; i < len1; i++) {
ans[i] = map.getOrDefault(nums1[i], -1);
}
return ans;
}
}