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-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
The newest version!
package g0401_0500.s0496_next_greater_element_i;
// #Easy #Array #Hash_Table #Stack #Monotonic_Stack #Programming_Skills_I_Day_5_Function
// #2022_07_21_Time_4_ms_(81.18%)_Space_43.7_MB_(77.46%)
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;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy