提交 edb2084f 编写于 作者: Z zak

【496.下一个更大元素I】

上级 36f59b6f
......@@ -181,4 +181,58 @@ vector<int> nextGreaterElements(vector<int>& nums) {
<img src="../pictures/qrcode.jpg" width=200 >
</p>
======其他语言代码======
\ No newline at end of file
======其他语言代码======
[ZakAnun](https://github.com/ZakAnun) 提供代码
```java
// 496.下一个更大元素
// 暴力解法
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] result = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) {
// 需要记录第一个数组每个元素在第二个数组中出现的位置
int index = 0;
for (int j = 0; j < nums2.length; j++) {
if (nums1[i] == nums2[j]) {
index = j;
break;
}
}
// 根据找到的位置往后遍历,若符合条件则记录到结果数组
for (int k = index; k < nums2.length; k++) {
if (nums2[k] > nums1[i]) {
result[i] = nums2[k];
break;
}
}
// 判断若对应位置结果依然为默认值,则将其修改为 -1
if (result[i] == 0) {
result[i] = -1;
}
}
return result;
}
// 分析: 暴力解法中需要确定数组1中每个元素在数组2中的下标而需要进行额外的遍历导致时间复杂度升高,
// 但若能够先罗列出全部的结果,然后从结果集中获取数组1中每个元素对应的下一个更大元素,就可以节省这部分时间(这里需要引用 HashMap 帮助我们记录结果,以便根据数组1获取。
// 单调栈解法
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Stack<Integer> stack = new Stack <>();
HashMap<Integer, Integer> map = new HashMap <>();
int[] result = new int[nums1.length];
for (int value : nums2) {
while (!stack.empty() && value > stack.peek()) {
map.put(stack.pop(), value);
}
stack.push(value);
}
while (!stack.empty()) {
map.put(stack.pop(), -1);
}
for (int i = 0; i < nums1.length; i++) {
result[i] = map.get(nums1[i]);
}
return result;
}
```
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册