496 下一个更大元素-01
暴力
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int len1=nums1.length;
int len2=nums2.length;
int[] ans=new int[len1];
for(int i=0;i<len1;i++){
//先找到nums[i]在num2[]中的对应位置
int pos=0;
while(pos<len2 && nums1[i]!=nums2[pos]){
pos++;
}
//找下一个比其大的值
while(pos<len2 && nums1[i]>=nums2[pos]){
pos++;
}
if(pos>=len2){
ans[i]=-1;
}else{
ans[i]=nums2[pos];
}
}
return ans;
}
}
时间复杂度
O
(
m
n
)
O(mn)
O(mn),其中
m
m
m是第一个数组的长度,
n
n
n第二个数组的长度,找数组1中某一个元素的下一个更大元素要遍历一遍数组2。
空间复杂度
O
(
1
)
O(1)
O(1)。
单调栈
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Deque<Integer> s = new LinkedList<>();
HashMap<Integer, Integer> map = new HashMap<>();
int[] ans = new int[nums1.length];
s.addLast(nums2[0]);
for (int i = 1; i < nums2.length; i++) {
while (!s.isEmpty() && s.getLast() < nums2[i]) {
Integer integer = s.removeLast();
map.put(integer, nums2[i]);
}
s.addLast(nums2[i]);
}
// while (!s.isEmpty()){
// map.put(s.removeLast(),-1);
// }
for (int i = 0; i < nums1.length; i++) {
ans[i] = map.getOrDefault(nums1[i], -1);
}
return ans;
}
}
时间复杂度
O
(
m
+
n
)
O(m+n)
O(m+n),分别遍历数组1和数组2各一次,对于数组2中的每个元素,进栈一次,出栈一次。
空间复杂度
O
(
n
)
O(n)
O(n),在遍历数组2的时候,需要使用栈和哈希表映射用来临时存储答案。