g0401_0500.s0496_next_greater_element_i.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java17 Show documentation
Show all versions of leetcode-in-java17 Show documentation
Java Solution for LeetCode algorithm problems, continually updating
package g0401_0500.s0496_next_greater_element_i;
// #Easy #Array #Hash_Table #Stack #Monotonic_Stack
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Map indexMap = new HashMap<>();
for (int i = 0; i < nums2.length; i++) {
indexMap.put(nums2[i], i);
}
for (int i = 0; i < nums1.length; i++) {
int num = nums1[i];
int index = indexMap.get(num);
if (index == nums2.length - 1) {
nums1[i] = -1;
} else {
boolean found = false;
while (index < nums2.length) {
if (nums2[index] > num) {
nums1[i] = nums2[index];
found = true;
break;
}
index++;
}
if (!found) {
nums1[i] = -1;
}
}
}
return nums1;
}
}