From 8fad92673f0cd593d483436cb718542e8fa60a3a Mon Sep 17 00:00:00 2001 From: zhicheng lee <904688436@qq.com> Date: Thu, 22 Sep 2022 22:23:24 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200496.=E4=B8=8B=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E6=9B=B4=E5=A4=A7=E5=85=83=E7=B4=A0I.md=20Java?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加另一种思路的Java代码,更加清晰简洁 --- problems/0496.下一个更大元素I.md | 26 +++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0496.下一个更大元素I.md b/problems/0496.下一个更大元素I.md index 3c948815..31e6f230 100644 --- a/problems/0496.下一个更大元素I.md +++ b/problems/0496.下一个更大元素I.md @@ -221,6 +221,32 @@ class Solution { return res; } } + +// 版本2 +class Solution { + public int[] nextGreaterElement(int[] nums1, int[] nums2) { + HashMap map = new HashMap<>(); + for (int i = 0; i < nums1.length; i++) { + map.put(nums1[i], i); + } + + int[] res = new int[nums1.length]; + Stack stack = new Stack<>(); + Arrays.fill(res, -1); + + for (int i = 0; i < nums2.length; i++) { + while (!stack.isEmpty() && nums2[stack.peek()] < nums2[i]) { + int pre = nums2[stack.pop()]; + if (map.containsKey(pre)) { + res[map.get(pre)] = nums2[i]; + } + } + stack.push(i); + } + + return res; + } +} ``` Python3: ```python