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:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For number 2 in the first array, the next greater number for it in the second array is 3.
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
給你兩個(gè)數(shù)組卜范,第一個(gè)數(shù)組是第二個(gè)的子集劣摇,且每個(gè)元素都是唯一的哩都。要你求數(shù)組一對(duì)應(yīng)位置之后的第一個(gè)比他大的數(shù)咧织。
嗯嗯,惨篱,最容易的想法應(yīng)該是對(duì)于每個(gè)位置進(jìn)行暴力匹配凤薛,時(shí)間應(yīng)該是O( N2)座泳,但是仔細(xì)想想的話,每個(gè)數(shù)都是不同的這個(gè)大好條件沒有用到洒沦。
那么反過來思考一下如何豹绪?我們之前是去找比他大的元素,那么給定一個(gè)元素,我們?nèi)フ冶人〉脑貢?huì)如何呢瞒津?
答案是可以的蝉衣,而且相當(dāng)好。我們用一個(gè)hashmap去映射元素和對(duì)于位置之后第一個(gè)比他大的元素巷蚪。若元素比peek())要大病毡,簡單的pop元素到hashmap中去建立映射關(guān)系,最后將這個(gè)元素保存到stack的棧頂以恢復(fù)降序屁柏,如果元素比peek()要小啦膜,那么我們把它存放到一個(gè)stack的棧頂做新的peek,這樣這個(gè)stack中的元素是以降序排列的淌喻,我們只要pop()出所有比它小的元素即可僧家。這樣的話充分利用了有序性和stack的FILO的性質(zhì)。
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
HashMap<Integer,Integer> map = new HashMap<>();
Stack<Integer> stack = new Stack<>();
int[] result = new int[nums1.length] ;
for(int i = 0 ;i<nums2.length;i++)
{
while(!stack.isEmpty()&&stack.peek()<nums2[i])
{
map.put(stack.pop(),nums2[i]);
}
stack.push(nums2[i]);
}
for(int i = 0 ;i<nums1.length;i++)
{
result[i]=map.getOrDefault(nums1[i],-1);
}
return result;
}
}