题目:
https://leetcode-cn.com/problems/next-greater-element-i/
解法一:
for循环暴力求解,先在nums2数组中找到nums1数组中的值,再向后寻找第一个更大元素。时间复杂度:O(M*N)
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] resultArr = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) {
int temp = -1;
int index = -1;
for (int j = 0; j < nums2.length; j++) {
if (nums2[j] == nums1[i]) {
index = j;
}
if (index != -1 && nums2[j] > nums1[i]) {
temp = nums2[j];
break;
}
}
resultArr[i] = temp;
}
return resultArr;
}
解法二:
利用单调栈,先忽略nums1,对nums2中每个元素,求出其下一个更大元素,可以用hash表或者hashmap映射两者关系,最后遍历nums1从hash表中找出答案。时间复杂度:O(M+N)
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] resultArr = new int[nums1.length];
int[] tempArr = new int[10000 + 5];
Arrays.fill(tempArr, -1);
Stack<Integer> stack = new Stack<>();
for (int value : nums2) {
while (!stack.isEmpty() && value > stack.peek()) {
tempArr[stack.pop()] = value;
}
stack.push(value);
}
for (int i = 0; i < nums1.length; i++) {
resultArr[i] = tempArr[nums1[i]];
}
return resultArr;
}