JS算法-下一个更大元素 I

394 阅读2分钟

本题来自leetcode 第 496 题

题目要求

给你两个 没有重复元素 的数组 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 。

示例 2:

输入: nums1 = [2,4], nums2 = [1,2,3,4].
输出: [3,-1]
解释:
    对于 num1 中的数字 2 ,第二个数组中的下一个较大数字是 3 。
    对于 num1 中的数字 4 ,第二个数组中没有下一个更大的数字,因此输出 -1 。

提示:

1 <= nums1.length <= nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 104
nums1和nums2中所有整数 互不相同
nums1 中的所有整数同样出现在 nums2 中

解题思路

本题可以用循环嵌套,也可以用单调栈来解决

代码展示

方法一:暴力解法

var nextGreaterElement = function(nums1, nums2) {
  const len1 = nums1.length;
  const len2 = nums2.length;
  const res = new Array(len1).fill(-1);
  for(let i = 0; i < len1; i++) {
    let index = nums2.indexOf(nums1[i]);
    while (index < len2) {
      if (nums2[index] > nums1[i]) {
        res[i] = nums2[index];
        break;
      }
      index++;
    }
  }
  return res;
};

暴力解法的时间复杂度为O(mn),时间复杂度为O(n)。

截屏2021-04-27下午11.36.40.png

方法二:单调栈解法

var nextGreaterElement = function(nums1, nums2) {
  const len1 = nums1.length;
  const len2 = nums2.length;
  const map = new Map();
  const stack = [];
  const res = [];
  // 此循环复杂入栈操作
  for(let i = 0; i < len2; i++) {
    const t = nums2[i];
    // while循环负责比对,并且出栈的操作,找到时,给map设置key->value
    while(stack.length && t > stack[stack.length - 1]) {
      const top = stack.pop();
      map.set(top, t);
    }
    stack.push(t);
  }
  for(let i = 0; i < len1; i++) {
    const val = map.get(nums1[i]);
    res[i] = val ? val : -1;
  }
  return res;
};

截屏2021-04-28上午9.42.16.png

单调栈解法的时间复杂度为O(m+n),空间复杂度为O(m)。

总结

单调栈解法,会对两个数组分别遍历一轮,不需要重复遍历。显然,此方法性能更好。