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
Analysis
时空复杂度都是O(n).
Last updated
Was this helpful?