496.下一个更小元素I(javascript)496.NextGreaterElementI
原创nums1 中数字 x 的 下一个更大的元素 是指 x 在 nums2 中的对应位置 右侧 的 第一个 比 x 大型元素。
给你两个 无重复元素 的数组 nums1 和 nums2 ,下标从 0 开始计数,其中nums1 是 nums2 的子集。
对于每个 0 <= i < nums1.length ,找出满意度 nums1[i] == nums2[j] 的下标 j ,并且在 nums2 确定 nums2[j] 的 下一个更大的元素 。如果不存在下一个更大的元素,那么本次查询的答案是 -1 。
返回长度 nums1.length 的数组 ans 作为答案,满足 ans[i] 如上所述 下一个更大的元素 。
The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.
You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.
For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.
Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.
示例 1:
输入:nums1 = [4,1,2], nums2 = [1,3,4,2].
输出:[-1,3,-1]
解释:nums1 中每个值的下一个更大的元素如下所述:
- 4 ,用粗体斜体标识,nums2 = [1,3,4,2]。不存在下一个更大的元素,所以答案是 -1 。
- 1 ,用粗体斜体标识,nums2 = [1,3,4,2]。下一个更大的元素是 3 。
- 2 ,用粗体斜体标识,nums2 = [1,3,4,2]。不存在下一个更大的元素,所以答案是 -1 。
示例 2:
输入:nums1 = [2,4], nums2 = [1,2,3,4].
输出:[3,-1]
解释:nums1 中每个值的下一个更大的元素如下所述:
- 2 ,用粗体斜体标识,nums2 = [1,2,3,4]。下一个更大的元素是 3 。
- 4 ,用粗体斜体标识,nums2 = [1,2,3,4]。不存在下一个更大的元素,所以答案是 -1 。
提示:
1 <= nums1.length <= nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 104
nums1和nums2中的所有整数 互不相同
nums1 相同中的所有整数都出现在 nums2 中
根据问题的含义:
- 对nums1遍历,每个元素都位于nums2中的下标;let j = nums2.indexOf(nums1[i])
- 对nums2循环,循环范围[j,len2),当发现第一个比率nums1[i]大,取最大值,跳出循环;j++;
- 对于max = -1当通过循环找到较大的值时,它将被替换。nums1[i]; 未找到,已返回-1
-
因为在每个循环之后,nums1[i]元素将不使用,因此为了优化代码,请直接nums1[i]进行修改
var nextGreaterElement = function (nums1, nums2) { let len1 = nums1.length let len2 = nums2.length for (let i = 0; i < len1; i++) { let j = nums2.indexOf(nums1[i]) let max = -1 while (j < len2) { if (nums2[j] > nums1[i]) { max = Math.max(max, nums2[j]) j = len2 } j++ } nums1[i] = max } return nums1 };
leetcode: https://leetcode.cn/problems/next-greater-element-i/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除