Next Greater Element I
https://leetcode.com/problems/next-greater-element-i/description/
You are given two arrays(without duplicates)
nums1
andnums2
wherenums1
’s elements are subset ofnums2
. Find all the next greater numbers fornums1
's elements in the corresponding places ofnums2
.The Next Greater Number of a numberxin
nums1
is the first greater number to its right innums2
. If it does not exist, output -1 for this number.
Thoughts
刚开始理解错了题意,以为是找比nums1各元素大的数。后来发现是找在nums2中排在该元素右边的遇到的第一个最大的数。还有个比较容易弄错的是nums1如何排列实际上没有任何关系。
stack的另一个应用,只存递减的元素,把不符合的抛出。新push进去的即那些被抛出的右边遇到的第一个比它们大的元素。
Code
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Map<Integer, Integer> map = new HashMap<>();
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < nums2.length; i++) {
if (stack.isEmpty()) {
stack.push(nums2[i]);
} else {
while (!stack.isEmpty() && nums2[i] > stack.peek()) {
map.put(stack.pop(), nums2[i]);
}
stack.push(nums2[i]);
}
}
int[] res = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) {
if (map.containsKey(nums1[i])) {
res[i] = map.get(nums1[i]);
} else {
res[i] = -1;
}
}
return res;
}
}
Analysis
时空复杂度都是O(n).
Last updated
Was this helpful?