class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> map = new HashMap();
Deque<Integer> stack = new ArrayDeque<>(); // faster than stack
for(int num : nums2) { // scans each no. in nums2
while(!stack.isEmpty() && stack.peek() < num) {
map.put(stack.pop(), num);
}
stack.push(num);
}
int[] result = new int[nums1.length]; // num1 jitna length ka answer hona chaiye!
for(int i=0; i<nums1.length; i++) {
result[i] = map.getOrDefault(nums1[i], -1); // if it exists, return value nums1[i] else return -1
}
return result;
}
}
No comments:
Post a Comment