You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1’s elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.
Example 1:
Example 2:
Note:
All elements in nums1 and nums2 are unique.
The length of both nums1 and nums2 would not exceed 1000.
解法1:Stack + HashMap: O(N) Time + O(N) Space
很好的一道题,主要的思路是在扫描的过程中得出每一个element对应的next greater element。 然后在hashmap中查找所需要的结果。
一次遍历找出next greater element的思路是[A,B] 如果B比A大那么B就是A对应的结果。如果B比A小的话要找出第一个比B大的数才是B的结果,而A要等到比A自己大的才可以。
那么试想,如果碰到一个递减数列[5,4,3,2,1]如果出现一个6,比前面所有的数都大,这个时候这个6就是所有数的NGE。所以有此我们可以用一个stack来维护递减的数列,只要下一个数比stack的top大,那么top值得NGE就是当前的值。
不停的弹出stack的值直到top的值比当前的值大为止。
Java