054 · Next Greater Element I

algorithm
Published

July 7, 2026

Problem

给定两个整数数组 nums1nums2

nums1 中的每个元素都出现在 nums2 中,并且两个数组中的元素都互不相同。

nums1 中的每个元素 x,需要在 nums2 中找到 x 的位置,然后继续向右看,找到第一个比 x 更大的元素。

如果右边存在这样的元素,就把它作为 x 的答案。

如果右边不存在比 x 更大的元素,就把 -1 作为 x 的答案。

请按 nums1 的顺序,返回每个元素对应的答案数组。

例如:

nums1 = [4, 1, 2]
nums2 = [1, 3, 4, 2]

nums2 中:

  • 4 的右边只有 2,没有更大的元素,所以答案是 -1
  • 1 的右边第一个更大的元素是 3
  • 2 的右边没有元素,所以答案是 -1

所以返回:

[-1, 3, -1]

Examples

示例 1

Input:  nums1 = [4, 1, 2], nums2 = [1, 3, 4, 2]
Output: [-1, 3, -1]

解释:42nums2 右侧都没有更大的元素;1 右侧第一个更大的元素是 3

示例 2

Input:  nums1 = [2, 4], nums2 = [1, 2, 3, 4]
Output: [3, -1]

解释:2nums2 右侧第一个更大的元素是 34 右侧没有更大的元素。

示例 3

Input:  nums1 = [1, 3, 5], nums2 = [6, 5, 4, 3, 2, 1, 7]
Output: [7, 7, 7]

解释:135nums2 右侧第一个更大的元素都是 7

Constraints

  • \(1 \leq\) nums1.length \(\leq\) nums2.length \(\leq 1000\)
  • \(0 \leq\) nums1[i], nums2[i] \(\leq 10^4\)
  • nums1nums2 中的所有整数互不相同
  • nums1 中的所有整数都出现在 nums2