解题关键字:单调栈
问题描述
给定一个数组,有正有负。对于每个元素,在后续数组中找到第一个大于此元素的数。
我的解答
我们最先想到的肯定是暴力解,遍历每一个元素,然后遍历后续数组,找到满足要求的数,O(n2)复杂度。
这是一类问题,最优解是用单调栈来解决。
单调栈,顾名思义,就是在栈内是单调的有序的。那用单调栈找数组中的顺序数or逆序数就容易多了。比如要找上面问题描述中的顺序数,我们就依次遍历数组,小于栈顶元素就入栈;大于栈顶元素出栈,(出栈元素,当前元素)这就是我们要找的顺序数。
代码如下:
class Solution {
public int[] firstBigger(int[] nums) {
int len = nums.length;
int[] result = new int[len];
Deque<Integer> stack = new LinkedList<>();
for(int i=0;i<len;i++){
int now = nums[i];
while(!stack.isEmpty() && now > nums[stack.peek()]){
int top = stack.pop();
result[top] = now;
}
stack.push(i);
}
return result;
}
}
类似的题
有很多类似的题,比如下面这一道
581. 最短无序连续子数组
面对这个题,最简单的思想应该是:从左向右依次遍历,每遍历一个元素就在后续数组里寻找,有没有比当前元素小的,有就立即退出循环,标记这个元素为最短无序子序列的开始。再从右向左依次遍历,同理找到最短无需子序列的结束。复杂度O(n2),有点高。
那要怎么优化一下呢?我从左向右遍历,就是要找到第一对逆序数(这里的第一这样理解:逆序数有左右两个元素,第一的意思是左元素的索引是第一),简单的方法就是双层循环遍历,那可不可以一次循环就找到呢?当然可以,用上面讲的方法呀!
但有个细节要处理一下:我们第一次出栈的不一定是无序数组的开头,可能是中间的元素,比如(2,4,5,4,3,6,7),第一次出栈的最后一个元素是5,所以要继续遍历后边的3,才能让4出栈。
从右向左思想类似。
代码贴出来
class Solution {
public int findUnsortedSubarray(int[] nums) {
int len = nums.length;
int start_index = len, end_index = -1;
Deque<Integer> stack = new LinkedList<>();
for(int i=0; i<len; i++){
if(stack.isEmpty() || nums[i] >= nums[stack.peek()]){
stack.push(i);
}else{
while(!stack.isEmpty() && nums[i] < nums[stack.peek()]){
int a = stack.pop();
if(a < start_index){
start_index = a;
}
}
//stack.push(i);//这里入不入都可以,因为此元素一定不是 第一个逆序数的左元素
}
}
while(!stack.isEmpty()){
stack.pop();
}
for(int i=len-1; i>=0; i--){
if(stack.isEmpty() || nums[i] <= nums[stack.peek()]){
stack.push(i);
}else{
while(!stack.isEmpty() && nums[i] > nums[stack.peek()]){
int a = stack.pop();
if(a > end_index){
end_index = a;
}
}
//stack.push(i);
}
}
if(start_index == len){
return 0;
}
return end_index - start_index + 1;
}
}