mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
更新 0496.下一个更大元素I.md Java代码
添加另一种思路的Java代码,更加清晰简洁
This commit is contained in:
@ -221,6 +221,32 @@ class Solution {
|
|||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 版本2
|
||||||
|
class Solution {
|
||||||
|
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
|
||||||
|
HashMap<Integer, Integer> map = new HashMap<>();
|
||||||
|
for (int i = 0; i < nums1.length; i++) {
|
||||||
|
map.put(nums1[i], i);
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] res = new int[nums1.length];
|
||||||
|
Stack<Integer> 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:
|
Python3:
|
||||||
```python
|
```python
|
||||||
|
Reference in New Issue
Block a user